Skip to content

Latest commit

 

History

History
45 lines (42 loc) · 1.81 KB

131. Palindrome Partitioning.md

File metadata and controls

45 lines (42 loc) · 1.81 KB

思路

由于是求所有情况,那一般就可以用DFS来考虑(要形成这种条件反射)

我们从s的开头往后遍历,用out数组来存放中间结果: 将已经检测好的回文子串放到字符串数组out中;每当s遍历完了之后, 将out加入结果res中。那么在DFS递归函数中我们必须要知道当前遍历到的位置,可用变量start来表示,所以在DFS递归函数中, 如果start等于字符串s的长度,说明已经遍历完成(递归出口),将out加入结果数组res中,并返回。否则就从start处开始进行深度优先搜索, 即判断一个字符,或两个字符,或三个字符...是否是回文串,若子串是回文串,那么我们将其加入out,并且调用DFS递归函数, 注意DFS后要恢复out的状态。

C++

class Solution {
private:
    bool isPalindrome(string &s, int low, int high){ // 判断s[start,...,end]是否是回文串
        while(low < high){
            if(s[low] != s[high]) return false;
            low++;
            high--;
        }
        return true;
    }
    void DFS(vector<vector<string>> &res, vector<string> &out, string &s, int start){
        if(start == s.size()){
            res.push_back(out);
            return;
        }
        for(int i = start; i < s.size(); i++){
            if(isPalindrome(s, start, i)){
                out.push_back(s.substr(start, i-start+1));
                DFS(res, out, s, i + 1);
                out.pop_back(); // 注意DFS后要恢复out的状态
            }
        }
    }

public:
    vector<vector<string>> partition(string s) {
        vector<vector<string>>res{};
        vector<string>out{};
        DFS(res, out, s, 0);
        return res;
    }
};