forked from ash638/code-for-hactoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDP_LCS.cpp
More file actions
37 lines (30 loc) · 1.04 KB
/
DP_LCS.cpp
File metadata and controls
37 lines (30 loc) · 1.04 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
// Longest Common Subsequence
#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
int dp[105][105];
int longest_commom_subsequence(int i,int j,string s1,string s2){
if(i<=0||j<=0){ // Base condition
return 0;
}
if(dp[i][j]!=-1){ // if already solved the case directly return the solution
return dp[i][j];
}
int ans=0;
ans = max(ans,longest_commom_subsequence(i-1,j,s1,s2));
ans = max(ans,longest_commom_subsequence(i,j-1,s1,s2));
ans = max(ans,longest_commom_subsequence(i-1,j-1,s1,s2)+ (s1[i-1]==s2[j-1])) ;
return dp[i][j]=ans;
}
int main(){
memset(dp,-1,sizeof(dp)); // initializing dp value by -1
int t;
cin>>t;
while(t--){
string test_case1,test_case2;
cin>>test_case1>>test_case2;
cout<<longest_commom_subsequence(test_case1.length(),test_case2.length(),test_case1,test_case2);
}
}
// Time complexity : O(n*m)
// n and m are length of strings