-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlongest common subsequence.cpp
More file actions
77 lines (72 loc) · 1.34 KB
/
longest common subsequence.cpp
File metadata and controls
77 lines (72 loc) · 1.34 KB
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
#include<bits/stdc++.h>
using namespace std;
int lcs(char* s1,char* s2)
{
if(s1[0]=='\0' || s2[0]== '\0')
{
return 0;
}
if(s1[0]==s2[0])
{
return 1+lcs(s1+1, s2+1);
}
else
{
int option1=lcs(s1,s2+1);
int option2=lcs(s1+1,s2);
return max(option1,option2);
}
}
int lcs2helper(char* s1, char* s2,int m, int n, int ** dp)
{
if(m==0 || n==0)
{
return 0;
}
if(dp[m][n]>-1)
{
return dp[m][n];
}
int ans;
if(s1[0]==s2[0])
{
ans= 1+lcs2helper(s1+1, s2+1,m-1,n-1,dp);
}
else
{
int option1=lcs2helper(s1,s2+1,m,n-1,dp);
int option2=lcs2helper(s1+1,s2,m-1,n,dp);
ans= max(option1,option2);
}
dp[m][n]=ans;
return ans;
}
int lcs2(char* s1, char* s2)
{
int m=strlen(s1);
int n=strlen(s2);
int** dp =new int*[m+1];
for(int i=0;i<=m;i++)
{
dp[i]=new int[n+1];
for(int j=0;j<=n;j++)
{
dp[i][j]=-1;
}
}
int ans=lcs2helper(s1,s2,m,n,dp);
for(int i=0;i<=m;i++)
{
delete[] dp[i];
}
delete [] dp;
return ans;
}
int main()
{
char a[100],b[100];
cin>>a;
cin>>b;
cout<<lcs2(a,b)<<endl;
//cout<<lcs(a,b)<<endl;
}