// User function Template for Java class Node { int i; int j; String str; Node(int i, int j, String str) { this.i = i; this.j = j; this.str = str; } } class Solution { // TreeSet automatically keeps elements sorted lexicographically. Set set = new TreeSet<>(); /** Memoization **/ public List allLCS(String s1, String s2) { int n = s1.length(); int m = s2.length(); // step-1 create a matrix int[][] t = new int[n+1][m+1]; // step-2 initialise the matrix acc. to base condition for(int i=0; i list = new ArrayList<>(); list.addAll(set); return list; } public void printAllLCS(String s1, String s2, int i, int j, int[][] t, String str) { if(i == 0 || j == 0) { set.add(new StringBuilder(str).reverse().toString()); return; } if(s1.charAt(i-1) == s2.charAt(j-1)) { printAllLCS(s1, s2, i-1, j-1, t, str + s1.charAt(i-1)); } else { // If both equal → explore both paths (this creates multiple LCS). if(t[i-1][j] >= t[i][j-1]) printAllLCS(s1, s2, i-1, j, t, str); if(t[i][j-1] >= t[i-1][j]) printAllLCS(s1, s2, i, j-1, t, str); } } /** Top-Down Approach **/ public List allLCS(String s1, String s2) { int n = s1.length(); int m = s2.length(); // step-1 create a matrix int[][] t = new int[n+1][m+1]; // step-2 initialise the matrix acc. to base condition for(int i=0; i st = new Stack<>(); st.push(new Node(n, m, "")); while(!st.isEmpty()) { Node curr = st.pop(); int i = curr.i; int j = curr.j; String s = curr.str; if(i == 0 || j == 0) { set.add(new StringBuilder(s).reverse().toString()); continue; } if(s1.charAt(i-1) == s2.charAt(j-1)) st.push(new Node(i-1, j-1, s + s1.charAt(i-1))); else { // explore both paths if(t[i-1][j] >= t[i][j]) st.push(new Node(i-1, j, s)); if(t[i][j-1] >= t[i][j]) st.push(new Node(i, j-1, s)); } } List list = new ArrayList<>(); list.addAll(set); return list; } }