-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLCSstring_2memoisation.cpp
More file actions
47 lines (40 loc) · 883 Bytes
/
LCSstring_2memoisation.cpp
File metadata and controls
47 lines (40 loc) · 883 Bytes
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
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int LCS(string x, string y, int m, int n, int count)
{
map<vector<int>, int> memo;
int maxVal =0;
vector<int> key{m,n,count};
if(n==0 || m==0)
{
return count;
}
if(memo.find(key)!=memo.end())
{
auto it = memo.find(key);
return it->second;
}
if(x[m-1] == y[n-1])
{
count++;
int result = LCS(x,y,m-1,n-1,count);
memo.insert({{m,n,count},result});
return result;
}
else
{
int result = max(count,max(LCS(x,y,m-1,n,0),LCS(x,y,m,n-1,0)));
memo.insert({{m,n,count},result});
return result;
}
}
int main()
{
string x = "abcdls";
string y = "abedls";
int m = x.length();
int n = y.length();
int length = LCS(x,y,m,n,0);
cout<<"Length "<<length<<endl;
}