[leetcode] 131. Palindrome Partitioning

9 篇文章 0 订阅
4 篇文章 0 订阅

Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:

Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

解法1 DFS,回溯

利用DFS,递归函数helper,从start开始,搜索每个子字符串,如果是回文就加入到out中,递归下一个位置start+1;

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

解法2:dp+DFS

利用一个dp二维数组表示是否为回文子串,不用调用回文判断函数,降低时间复杂度。

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        vector<string> out;
        int n = s.size();
        vector<vector<bool>> dp(n,vector<bool>(n));
        for(int i=0;i<n;i++){
            for(int j = 0; j <= i; j ++)
                if(s[i]== s[j] && (i-j<=2 || dp[j+1][i-1]))
                    dp[j][i] = 1;
        }
        helper(res,out,dp,0,s);
        return res;
    }
    
    void helper(vector<vector<string>>& res, vector<string>& out, vector<vector<bool>>& dp, int start, string s){
        if(start == s.size()){
            res.push_back(out);
            return ;
        }
        for(int i=start;i<s.size();i++){
            if (!dp[start][i]) continue;
            out.push_back(s.substr(start, i - start + 1));
            helper(res,out,dp,i+1,s);
            out.pop_back();
        }
    }
    
};

参考

https://www.cnblogs.com/grandyang/p/4270008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值