File tree Expand file tree Collapse file tree 1 file changed +72
-0
lines changed
Dynamic Programming/Longest Common Subsequence Expand file tree Collapse file tree 1 file changed +72
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ int dp[50 ][50 ];
5
+ // use recursion to print all possible solutions
6
+ // set to store the possible lcs in non-repeating and in increasing order(alphabetically)
7
+ set<string> getAllLCS (string a,string b,int n,int m)
8
+ {
9
+ set<string> ans;
10
+
11
+ if (n==0 || m==0 )
12
+ {
13
+ ans.insert (" " );
14
+ return ans;
15
+ }
16
+
17
+ if (a[n-1 ]==b[m-1 ])
18
+ {
19
+ set<string> tmp=getAllLCS (a,b,n-1 ,m-1 );
20
+ for (string s:tmp)
21
+ ans.insert (s+a[n-1 ]);
22
+
23
+ }
24
+
25
+
26
+ else
27
+ {
28
+ if (dp[n-1 ][m]>=dp[n][m-1 ])
29
+ ans=getAllLCS (a,b,n-1 ,m);
30
+
31
+
32
+ if (dp[n][m-1 ]>=dp[n-1 ][m])
33
+ {
34
+ set<string> tmp=getAllLCS (a,b,n,m-1 );
35
+
36
+ ans.insert (tmp.begin (),tmp.end ());
37
+ }
38
+ }
39
+
40
+ return ans;
41
+
42
+
43
+ }
44
+ int main ()
45
+ {
46
+ string a,b;
47
+ cin>>a>>b;
48
+
49
+ int n=a.size ();
50
+ int m=b.size ();
51
+
52
+
53
+
54
+ memset (dp,0 ,sizeof (dp));
55
+
56
+ // construct the lcs matrix
57
+ for (int i=1 ;i<=n;i++)
58
+ {
59
+ for (int j=1 ;j<=m;j++)
60
+ {
61
+ if (a[i-1 ]==b[j-1 ])
62
+ dp[i][j]=dp[i-1 ][j-1 ]+1 ;
63
+ else
64
+ dp[i][j]=max (dp[i-1 ][j],dp[i][j-1 ]);
65
+ }
66
+ }
67
+
68
+ set<string> ans=getAllLCS (a,b,n,m);
69
+
70
+ for (auto it:ans)
71
+ cout<<it<<" " ;
72
+ }
You can’t perform that action at this time.
0 commit comments