-
Notifications
You must be signed in to change notification settings - Fork 0
/
Longest common Subsequence.cpp
85 lines (65 loc) · 1.8 KB
/
Longest common Subsequence.cpp
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//1143. Longest Common Subsequence Bottom-up
class Solution {
public:
int lcs(string text1, string text2,int m,int n,int **dp){
if(m==0)
return 0;
if(n==0)
return 0;
if(dp[m][n]!=-1)
return dp[m][n];
if(text1[m-1]==text2[n-1]){
dp[m][n]=1+lcs(text1,text2,m-1,n-1,dp);
return dp[m][n];}
else if(text1[m-1]!=text2[n-1]) {
dp[m][n]=max(lcs(text1,text2,m,n-1,dp),lcs(text1,text2,m-1,n,dp));
return dp[m][n];
}
else return dp[m][n];
}
int longestCommonSubsequence(string text1, string text2) {
int m=text1.length();
int n=text2.length();
int **dp=new int*[m+1];
for(int i=0;i<m+1;i++){
dp[i]=new int[n+1];
}
for(int i=1;i<m+1;i++){
for(int j=1;j<n+1;j++){
dp[i][j]=-1;
}
}
int t= lcs(text1,text2,m,n,dp);
return t;
}
};
//TOP-DOWN
class Solution {
public:
int lcs(string text1, string text2,int m,int n,int **dp){
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(text1[m-i]==text2[n-j])
dp[i][j]=1+dp[i-1][j-1];
else
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
return dp[m][n];
}
int longestCommonSubsequence(string text1, string text2) {
int m=text1.length();
int n=text2.length();
int **dp=new int*[m+1];
for(int i=0;i<m+1;i++){
dp[i]=new int[n+1];
}
for(int i=0;i<m+1;i++){
for(int j=0;j<n+1;j++){
dp[i][j]=0;
}
}
int t= lcs(text1,text2,m,n,dp);
return t;
}
};