动态规划基础篇
例一:最长公共子串
特点:连续
In:5 3 1 2 3 4 OUT:4
2 3 2 5 3 1 2
思路:一一比对,相同填1,不同填0:标蓝的即为最长
5 | 3 | 1 | 2 | 3 | 4 | |
2 | 0 | 0 | 0 | 1 | 0 | 0 |
3 | 0 | 1 | 0 | 0 | 1 | 0 |
2 | 0 | 0 | 0 | 1 | 0 | 0 |
5 | 1 | 0 | 0 | 0 | 0 | 0 |
3 | 0 | 1 | 0 | 0 | 1 | 0 |
1 | 0 | 0 | 1 | 0 | 0 | 0 |
2 | 0 | 0 | 0 | 1 | 0 | 0 |
找出矩阵中最大的数即可
5 | 3 | 1 | 2 | 3 | 4 | |
2 | 0 | 0 | 0 | 1 | 0 | 0 |
3 | 0 | 1 | 0 | 0 | 1 | 0 |
2 | 0 | 0 | 0 | 1 | 0 | 0 |
5 | 1 | 0 | 0 | 0 | 0 | 0 |
3 | 0 | 2 | 0 | 0 | 1 | 0 |
1 | 0 | 0 | 3 | 0 | 0 | 0 |
2 | 0 | 0 | 0 | 4 | 0 | 0 |
1 for(int i=1;i<=lenx;i++) 2 for(int j=1;j<=leny;j++) 3 { 4 if(x[i]==y[j]) f[i][j]=f[i-1][j-1]+1; //左上角的数+1 5 else f[i][j]=0; 6 }
再找出矩阵中的最大数 即为所求
例二:最长公共子序列
特点:非连续