Longest Common Subsequence - DP on Strings
Problem Link:
https://www.codingninjas.com/studio/problems/longest-common-subsequence_624879?utm_source=striver&utm_medium=website&utm_campaign=a_zcoursetuf
My approach:
Code:
int helper(string s, string t, int ind1, int ind2, vector<vector<int>> &dp){
if(ind1==0 || ind2==0){
return 0;
}
if(dp[ind1][ind2]!=-1){
return dp[ind1][ind2];
}
int ans = 0;
if(s[ind1-1]==t[ind2-1]){
ans = 1 + helper(s,t,ind1-1,ind2-1,dp);
}else{
int a = helper(s,t,ind1-1,ind2,dp);
int b = helper(s,t,ind1,ind2-1,dp);
ans = max(a,b);
}
dp[ind1][ind2] = ans;
return ans;
}
int lcs(string s, string t)
{
int n = s.size();
int m = t.size();
vector<vector<int>> dp(n+1, vector<int>(m+1,-1));
return helper(s,t,n,m,dp);
}