131. Palindrome Partitioning && 132. Palindrome Partitioning II

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

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

[
  ["aa","b"],
  ["a","a","b"]
]

本题为分割得到所有回文字符串,采用DFS即可


class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        if(s.empty()) return res;
        vector<string> temp;
        dfs(res,temp,0,s);
        return res;
    }
    void dfs(vector<vector<string>>& res,vector<string>& temp,int index,string& s){
        if(index==s.size()){
            res.push_back(temp);
            return;
        }
        for(int i=index;i<s.size();i++){
            if(Palin(s,index,i)){
                temp.push_back(s.substr(index,i-index+1));
                dfs(res,temp,i+1,s);
                temp.pop_back();
            }
        }
    }
    bool Palin(const string &s,int start,int end){
        while(start<=end){
            if(s[start++]!=s[end--])
                return false;
        }
        return true;
    }
};




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.


在第二题中,再采用DFS会超时,因为第二题只需要求最小的切割数,而第一题是求所有的切割,有许多切割的切割数相同或者超过了,即使剪枝了也还是会超时

本题用到DP动态规划

步骤1 找到递推公式,假设bool dp[i][j]表示字符串下标从i到j是否为回文串   则dp[i][j]=(s[i]==s[j])&&((j-i>=1)||s[i+1][j-1])

如果i到j是回文的话,他依赖于i+1,j-1也为回文。而计算切割数的count数组,count[i]=min(1+count[j+1],count[i]),count[i]

代表从i开始的字符串的切割数

步骤2 确定循环顺序,因为j始终大于i,所以count[i]依赖于count[j],所以i的循环是逆序。


class Solution {
public:
    int minCut(string s) {
        vector<vector<int>> dp(s.size(),vector<int>(s.size(),0));
        vector<int> count(s.size()+1,0);
        for(int i=s.size()-1;i>=0;i--){
            count[i]=INT_MAX;
            for(int j=i;j<s.size();j++){
                if(s[i]==s[j]&&((j-i)<=1||dp[i+1][j-1])){
                    dp[i][j]=1;
                    count[i]=min(1+count[j+1],count[i]);
                }
            }
        }
        return count[0]-1;
    }
};


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值