(Leetcode_DP)5306. 让字符串成为回文串的最少插入次数

在这里插入图片描述

一般这种通过最少操作次数,求回文串都是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版本中没有这个模块,我运行调用不了。

发布了741 篇原创文章 · 获赞 185 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/Fire_to_cheat_/article/details/103855762