题解:
比较水的题目
dp[i][j]表示[i...j]最少改变几次变成回文字符串
那么有三种转移
dp[i][j] = dp[i+1][j-1] + s[i] != s[j]
dp[i][j] = dp[i+1][j] + 1(删除左边的字符,或者在右边添加一个字符与左边匹配)
dp[i][j] = dp[i][j-1] + 1(删除右边的字符,或者在左边添加一个字符与右边匹配)
#include <iostream> #include <cstring> #include <cstdio> using namespace std; char S[110]; int dp[110][110]; int dfs(int i, int j){ if(i >= j) return 0; if(dp[i][j] < 100) return dp[i][j]; dp[i][j] = min(dp[i][j], dfs(i+1, j) + 1); dp[i][j] = min(dp[i][j], dfs(i, j-1) + 1); dp[i][j] = min(dp[i][j], dfs(i+1, j-1) + (S[i] != S[j])); return dp[i][j]; } int main() { while(cin>>S){ int n = strlen(S); memset(dp, 1, sizeof(dp)); cout<<dfs(0, n-1)<<endl; } return 0; }