一般这种通过最少操作次数,求回文串都是DP求法最简单。
根据题意可以简单写出DP方程:
if s[i]==s[j]: dp[i][j]=dp[i+1][j-1]
else dp[i][j]=min(dp[i+1][j],dp[i][j-1])+1
那么下面就用c++和python分别实现:
class Solution {
public:
int minInsertions(string s) {
int n=s.length();
vector<vector<int>>dp(n,vector<int>(n));
for(int l=2;l<=n;++l)
{
for(int i=0,j=l-1;j<n;++i,++j)
{
dp[i][j]=s[i]==s[j]?dp[i+1][j-1]:min(dp[i+1][j]+1,dp[i][j-1]+1);
}
}
return dp[0][n-1];
}
};
from functools import lru_cache
class Solution(object):
def minInsertions(self, s):
"""
:type s: str
:rtype: int
"""
@lru_cache(None)
def dp(i,j):
if i>=j: return 0
return dp(i+1,j-1) if s[i]==s[j] else min(dp(i+1,j)+1,dp(i,j-1)+1)
return dp(0,len(s)-1)
lru_cache是一种可以记住前面操作的结果的缓存的模块,可用于记忆化搜索。
但是好像leetcode的python版本中没有这个模块,我运行调用不了。