LeetCode(Palindrome partition 2) 求将一个字符串划分成回文子串 需要分成的段数最少是多少

题目要求:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = "aab",
Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

思路 这道题可以用递归回溯,剪纸来解决 但是仍让很慢 会超时:

递归 代码:

class Solution {
public:
    
    int minCut(string s) {
        int res = 1 << 30;
        int cut_num = 0;
        DFS(s, 0, cut_num, res);
        return res - 1;      
    }
    
    void DFS(const string& str, int start, int& cut_num, int &res)
    {
        if (start == str.size()) {
            if(cut_num < res)
                res = cut_num;
            return;
        }
        
        if(cut_num > res)
            return;
        for (int i = str.size() - 1; i >= start; --i) {
            if(IsPalindrome(str, start, i))
            {
                ++cut_num;
                DFS(str, i + 1, cut_num, res);
                --cut_num;
            }
        }
    }
    
    bool IsPalindrome(const string& str, int start, int end)
    {
        while (start < end) {
            if(str[start] != str[end])
                return false;
            ++start;
            --end;
        }
        return true;
    }
};

其实,凡是要求最值得 多半是动态规划。设dp[i,j]表示 从i到j可以分成回文子串的最少段数,很容易得到 :

dp[i,j] = min(dp[i,k] + dp[k + 1, j]) i <= k <= j, 将其转换成一维动态规划.

dp[i]代表从i开始到n得最小cut数。 dp[i] = min(1 + dp[j + 1]) i <= j < n.

另外,在判断字符串是否是回文的时候 每次都通过扫描比较也比较浪费时间,可以用一个二维数组来保存已经计算过的结果,其实也是一个动态规划的过程,用is_palindrome[i][j]保存i到j之间的字符串是否是回文。初始化的时候:is_palindrome[i][j] = true , i == j;

is_palindrome[i][j] = (str[i] == str[j]) && is_palindrome[i + 1][j - 1];

动态规划代码:

int minCut(string s) {
        int len = s.size();
        int dp[len + 1];
        for (size_t i = 0; i <= len; ++i) {//初始化dp数组,初始值是将每个字母都切开
            dp[i] = len - i;
        }
        bool is_palindrome[len][len];
        memset(is_palindrome, false, sizeof(is_palindrome));
        for (int i = len - 1; i >= 0; --i) {
            for (int j = i; j < len; ++j) {
                if(s[i] == s[j] && ((j - i) < 2 ||//如果(j - i) < 2 说明只有一个字符肯定是回文
                                    is_palindrome[i + 1][j - 1]))
                {
                    is_palindrome[i][j] = true;
                    dp[i] = min(dp[i], dp[j + 1] + 1);
                }
            }
        }
        return dp[0] - 1;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值