Print all LCS sequences | Practice | GeeksforGeeks

You are given two strings s and t. Now your task is to print all longest common sub-sequences in lexicographical order.
Example 1:
Input: s = abaaa, t = baabaca
Output: aaaa abaa baaa

Example 2:
Input: s = aaa, t = a
Output: a

Your Task:
You do not need to read or print anything. Your task is to complete the function all_longest_common_subsequences() which takes string a and b as first and second parameter respectively and returns a list of strings which contains all possible longest common subsequences in lexicographical order.
 
Expected Time Complexity: O(n4)
Expected Space Complexity: O(K * n) where K is a constant less than n.
 
Constraints:
1 ≤ Length of both strings ≤ 50
+2
yoyogeshyo6351 month ago
Successfully submitted
 int countLcs(string s,string t){     int n=s.size();     int m=t.size();     vector<vector<int>>dp(n+1,vector<int>(m+1,-1));     for(int i=0;i<=n;i++){         for(int j=0;j<=m;j++){             if(i==0 || j==0)dp[i][j]=0;             else if(s[i-1]==t[j-1])dp[i][j]=1+dp[i-1][j-1];             else {                 dp[i][j]=max(dp[i-1][j],dp[i][j-1]);             }         }     }     return dp[n][m];}set<string>st;void helper(string s,string t,int i,int j,string &temp,vector<string>&ans,int count){       if(count==0){        if(st.find(temp)==st.end())            { st.insert(temp);            ans.push_back(temp);}                return;    }   if(i>=s.size() || j>=t.size())return;
       for(int r=i;r<s.size();r++){        for(int c=j;c<t.size();c++){            if(s[r]==t[c]){                                temp.push_back(s[r]);                helper(s,t,r+1,c+1,temp,ans,count-1);                temp.pop_back();            }        }    }} vector<string> all_longest_common_subsequences(string s, string t) {     // Code here    int a=countLcs(s,t);    vector<string>ans;    string temp="";   helper(s,t,0,0,temp,ans,a);   sort(ans.begin(),ans.end());    return ans; }
-1
sgupta95192 months ago
tle forever
0
avenvy3 months ago
Python Solution (All Test Case Passed)
def all_longest_common_subsequences(self, s, t):
	    MAX=100
	    dp=[[-1 for i in range(MAX)] for i in range(MAX)]
	    def lcs(str1, str2, len1, len2, i, j):
	        if (i == len1 or j == len2):
	            dp[i][j] = 0
	            return dp[i][j]
	        if (dp[i][j] != -1):
	            return dp[i][j]
	        ret = 0
	        if (str1[i] == str2[j]):
	            ret = 1 + lcs(str1, str2, len1, len2, i + 1, j + 1)
            else:
                ret = max(lcs(str1, str2, len1, len2, i + 1, j),
                  lcs(str1, str2, len1, len2, i, j + 1))
            dp[i][j] = ret
            return ret
        def printAll(str1, str2, len1, len2,cur, indx1, indx2, currlcs,lcslen):
            if (currlcs == lcslen):
                ans.append(cur)
                return
            if (indx1 == len1 or indx2 == len2):
                return
            for ch in range(ord('a'),ord('z') + 1):
                done = False
                for i in range(indx1,len1):
                    if (chr(ch)==str1[i]):
                        for j in range(indx2, len2):
                            if (chr(ch) == str2[j] and dp[i][j] == lcslen-currlcs):
                                new_cur = cur + chr(ch)
                                printAll(str1, str2, len1, len2, new_cur, i + 1, j + 1, currlcs + 1,lcslen)
                                done = True
                                break
                            if (done):
                                break
        len1,len2 = len(s),len(t)
        lcslen = lcs(s, t, len1, len2, 0, 0)
        global ans
        ans=[]
        printAll(s, t, len1, len2, "", 0, 0, 0,lcslen)
        ans.sort()
        w=set()
        pre=[]
        for i in ans:
            if i in w:
                continue
            else:
                pre.append(i)
                w.add(i)
        return pre
+2
shashankrustagii4 months ago
class Solution
{
	public:
	int dp[51][51];
	unordered_set<string> mp;
	unordered_set<string> st;
	void printLCS(vector<string> &ans,string s,string t,int i,int j,string str)
	{
	    if(i==0 or j==0)
	    {
	        reverse(str.begin(),str.end());
	        if(st.find(str)!=st.end()) return;
	        st.insert(str);
            ans.push_back(str);
            return;
	    }
	    string key;
	    key+=to_string(i);
	    key+=to_string(j);
	    key+=str;
	    if(mp.find(key)!=mp.end()) return;
	    mp.insert(key);
	    if(s[i-1]==t[j-1]) printLCS(ans,s,t,i-1,j-1,str+s[i-1]);
	    else if(dp[i-1][j]>dp[i][j-1]) printLCS(ans,s,t,i-1,j,str);
	    else if(dp[i-1][j]<dp[i][j-1])printLCS(ans,s,t,i,j-1,str);
	    else
	    {
	         printLCS(ans,s,t,i-1,j,str);
	         printLCS(ans,s,t,i,j-1,str);
	    }
	    return;
	}
	vector<string> all_longest_common_subsequences(string s, string t)
	{
		st.clear();
		int x=s.length();
		int y=t.length();
        for(int i=0;i<x+1;i++)
            for(int j=0;j<y+1;j++)
                if(!i or !j) dp[i][j]=0;
        for(int i=1;i<x+1;i++)
            for(int j=1;j<y+1;j++)
                if(s[i-1]!=t[j-1]) dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                else dp[i][j]=dp[i-1][j-1]+1;
        vector<string> ans;
        string str;
        int i=x;
        int j=y;
        printLCS(ans,s,t,i,j,str);
        sort(ans.begin(),ans.end());
        return ans;
        
        
	}
};
-5
saurabhkure167 months ago
class Solution
{
public:
int dp[101][101];
vector<string> res;

void storeAllLCS(int n, int m, string&s, string& t){

vector<vector<unordered_set<string>>> allLcs ( 101,
vector<unordered_set<string>>(101));
// We have taken unordered_set here so as to remove the possibility of redundant
// sub-LC sequences as we need only one occurrence of the sub-LCS
// Also unordered_set performs better compared to set/ordered_set
for(int i = 0; i <= n; ++i)
allLcs[i][0].insert("");

for(int i = 0; i <= m; ++i)
allLcs[0][i].insert("");

for(int i = 1; i <= n; ++i){
for(int j = 1; j <= m; ++j){
if( s[i-1] == t[j-1] ){
for( string prev : allLcs[i-1][j-1] ){
allLcs[i][j].insert(prev + s[i-1]);
}
}
else if( dp[i-1][j] == dp[i][j-1] ){
// Store all previous strings from both cells instead of just one
for( string prev : allLcs[i-1][j] )
allLcs[i][j].insert(prev);
for( string prev : allLcs[i][j-1] )
allLcs[i][j].insert(prev);
}
else{
// Get the maximum length set out of the two dp cells
unordered_set<string> best = ( dp[i-1][j] > dp[i][j-1] ) ?
( allLcs[i-1][j] ) : ( allLcs[i][j-1] );

for( string prev : best )
allLcs[i][j].insert(prev);
}
}
}
// Last element of allLcs will contain all LCS of max lengths
res = vector<string>( allLcs[n][m].begin(), allLcs[n][m].end() );
sort( res.begin(), res.end() );
}

void lcs_Tabulation(int n, int m, string& s, string& t){
memset(dp, 0, sizeof(dp));
for(int i = 0; i <= n; ++i){
for(int j = 0; j <= m; ++j){
if( i == 0 || j == 0 )
dp[i][j] = 0;
else if( s[i-1] == t[j-1] )
dp[i][j] = 1 + dp[i-1][j-1];
else
dp[i][j] = max( dp[i-1][j], dp[i][j-1] );
}
}

storeAllLCS(n, m, s, t);
}

vector<string> all_longest_common_subsequences(string s, string t)
{

if( s.size() == 0 || t.size() == 0 )
return res;

lcs_Tabulation(s.size(), t.size(), s, t);
return res;
}
};
-2
Amit Kumar8 months ago
Amit Kumar
https://practice.geeksforge...
0
Sourav9 months ago
Sourav
//This function will return all the LCS in reverse order.set<string> helper(string &s, string &t, int i, int j, vector<vector<int>> &dp){        if(i == 0 || j == 0){            set<string> ans;            ans.insert("");            return ans;        }         if(s[i-1] == t[j-1]){            set<string> ans;            char ch = s[i-1];            set<string> tempAns = helper(s, t, i-1, j-1, dp);            for(string s: tempAns){                string temp = ch + s;                ans.insert(temp);            }            return ans;        }         else{            set<string> temp1;            set<string>temp2;             if(dp[i][j-1] >= dp[i-1][j]){                temp1 = helper(s, t, i, j-1, dp);            }             if(dp[i-1][j] >= dp[i][j-1]){                temp2 = helper(s, t, i-1, j, dp);            }             for(string s : temp1){                temp2.insert(s);            }            return temp2;        }    }public:vector<string> all_longest_common_subsequences(string s, string t){    // Simple code to find LCS length....    int m = s.length();    int n = t.length();     vector<vector<int>>dp(m+1, vector<int>(n+1));     for(int i = 0; i<=m; i++){        for(int j = 0; j<=n; j++){            if(i == 0 || j == 0){                dp[i][j] = 0;            }             else if(s[i-1] == t[j-1]){                dp[i][j] = dp[i-1][j-1] + 1;            }            else{                dp[i][j] = max(dp[i-1][j], dp[i][j-1]);            }        }    }                     //This will return all the LCS but in reverse order.    set<string> help = helper(s, t, m , n, dp);    set<string> help1;                     //This will reverse the LCS's    for(string s : help){        reverse(s.begin(), s.end());        help1.insert(s);    }     vector<string> ans;    for(string s : help1){        ans.push_back(s);    }    return ans;}
0
Mohd Amir Khan9 months ago
Mohd Amir Khan
-1
naman jain9 months ago
naman jain
I am following this approach anybody else have done with this approach please connect:Approach 1)create dp table and find the length of LCS then we will use 2 loops to iterate complete table  and if we get LCS length in any cell of dp matrix then we will  call another method which will generate LCS string and add that to set and like wise do for all cell of dp which are equal to LCS  lenght and then add element of set   then to arraylist and return.
This is my approach I am getting some string  all are correct ans but complete set of answer which is expected is not comming can anyone help me with this approach.
0
PRATEEK JHABAK9 months ago
PRATEEK JHABAK
https://uploads.disquscdn.c...What is wrong in this? Please Help
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.