### 動態規划之LCS最長子序列問題

```#include <iostream>
#include <string>
using namespace std;

int max(int a, int b)
{
if(a > b)
return a;
else
return b;
}

/**

*/
//m,n is the length of string a,b
int lcs1(string &a, string &b, int m, int n)
{
if(m == 0 || n == 0)
return 0;
if(a[m-1] == b[n-1])
return lcs1(a, b, m-1, n-1) + 1;
else
return max(lcs1(a,b,m-1,n), lcs1(a,b,m,n-1));
}

/**

*/
int table[10][10] = {(0,0)};//全部初始化為0的table數組用於存儲子問題結果
int lcs2(string &a, string &b, int m, int n)
{
if(m == 0 || n == 0)
return 0;
if(table[m][n] != 0)
return table[m][n];
if(a[m-1] == b[n-1])
table[m][n] = lcs2(a, b, m-1, n-1) + 1;
else
table[m][n] = max(lcs2(a,b,m-1,n), lcs2(a,b,m,n-1));
return table[m][n];
}

/**

*/
string temp = ""; //全局string用於不斷加成lcs
int lcs3(string &a, string &b, int m, int n)
{
if(m == 0 || n == 0)
return 0;
if(a[m-1] == b[n-1])
{
temp += a[m-1];
return lcs3(a, b, m-1, n-1) + 1;
}
else
return max(lcs3(a,b,m-1,n), lcs3(a,b,m,n-1));
}

int main()
{
string a = "BACDAB";
cout<<lcs3(a,b,a.length(),b.length())<<endl;
cout<<temp<<endl;

return 0;
}
```