【leetcode】【medium】131. Palindrome Partitioning

131. 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"]
]

题目链接:https://leetcode-cn.com/problems/palindrome-partitioning/

思路

回溯法练习。

法一:回溯法

纸上模拟处理情况,写一个回溯法处理过程,再翻译成代码即可。

class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        if(s.size()<=0) return res;
        if (s.size()==1 ){
            vector<string> vec = {s};
            res.push_back(vec);
        }else{
            for( int i = 1; i<=s.size(); ++i){
                string head = s.substr(0,i);
                if(isPal(head)){
                    int sub = s.size()-i;
                    if(i == s.size()){
                        vector<string> vec = {s};
                        res.push_back(vec);
                    }else{
                        vector<vector<string>> vecs = partition(s.substr(i,s.size()-i));
                        if(vecs.size()>0){
                            for(int j = 0; j<vecs.size(); ++j){
                                vecs[j].insert(vecs[j].begin(), head);
                                res.push_back(vecs[j]);
                            }
                        }
                    }
                    
                }
            }
        }
        return res;
    }
    bool isPal(string s){
        if (s.size()<=0) return true;
        int l = 0, r = s.size()-1;
        while(l<r){
            if(s[l] != s[r]) return false;
            --r;
            ++l;
        }
        return true;
    }
};

代码优化

以上代码是将下层迭代结果向上返回,需在上层多做一次for循环;如果改成向下层传递结果,递归到底后直接储存最终结果,则能提高运行效率。

class Solution {
public:
    vector<vector<string>> res;
    vector<vector<string>> partition(string s) {
        if(s.size()<=0){
            return res;
        }
        vector<string> cur;
        trace(s, cur);
        return res;
    }
    void trace(string s, vector<string> &cur) {
        for( int i = 1; i<=s.size(); ++i){
            string head = s.substr(0,i);
            if(isPal(head)){
                cur.push_back(head);
                if(i == s.size()){
                    res.push_back(cur);
                }else{
                    trace(s.substr(i,s.size()-i), cur);
                }
                cur.pop_back();
            }
        }
        return;
    }
    bool isPal(string s){
        if (s.size()<=0) return true;
        int l = 0, r = s.size()-1;
        while(l<r){
            if(s[l] != s[r]) return false;
            --r;
            ++l;
        }
        return true;
    }
};

法二:回溯法,dp优化回文判断

先阶段练习回溯法,之后再来写这个代码。

发布了126 篇原创文章 · 获赞 2 · 访问量 3725

猜你喜欢

转载自blog.csdn.net/lemonade13/article/details/104496099