-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path21. Longest common subsequence Top down DP
67 lines (41 loc) · 1.14 KB
/
21. Longest common subsequence Top down DP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
--> Longest Common Subsequence Continued...
Top - down Approach -
Video Link : https://youtu.be/hR3s9rGlMTU
Code -->
#include<bits/stdc++.h>
using namespace std;
int LCS(string s1,string s2,int n,int m, vector<vector<int>> &t )
{
for(int i=0;i<n+1;i++){
t[i][0]=0;
}
for(int j=0;j<m+1;j++)
{
t[0][j]=0;
}
for(int i=1;i<n+1;i++)
{
for(int j=1;j<m+1;j++)
{
if(s1[i-1]==s2[j-1])
{
t[i][j]=1+t[i-1][j-1];
}
else{
t[i][j]= max(t[i][j-1] , t[i-1][j]);
}
}
}
return t[n][m];
}
int main()
{
int n, m; cin >> n >> m;
string s1, s2;
cin >> s1 >> s2;
// int t[n+1][m+1];
vector<vector<int>> t (n+1, vector<int> (m+1));
int ans = LCS(s1,s2,n,m,t);
cout<<ans;
return 0;
}