【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;
    }
};

法二:回溯法,dp優化迴文判斷

先階段練習回溯法,之後再來寫這個代碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章