朴素写法:
for (int i = 1; i <= len1; i++)
{
for (int j = 1; j <= len2; j++)
{
if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
printf("%d\n",dp[len1][len2]);
滚动数组优化:
int flag = 0;
for (int i = 1; i <= len1; i++)
{
flag = 1-flag;//如此操作后,flag相当于i,1-flag相当于i-1
for (int j = 1; j <= len2; j++)
{
if (str1[i-1] == str2[j-1]) dp[flag][j] = dp[1-flag][j-1] + 1;
else dp[i][j] = max(dp[1-flag][j],dp[flag][j-1]);
}
}
printf("%d\n",dp[flag][len2]);//最后输出的是dp[flag][len2],因为flag表示的是最新的i,也就是dp[len1][len2]。
//而1-flag是倒数第二个i,也就是dp[len1-1][len2];