Leetcode_Palindrome_Partitioning_DFS 算法

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"]
  ]
class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector <vector <string>>result;
        vector <string> path;
        dfs(result,s,path,0);
        return result;
    }
private:
    void dfs(vector <vector <string>>&result,string &s , vector<string> path,int cur){
    
        if(cur==s.size()){
            result.push_back(path);
            return;
        }
        
        for(int i=cur; i<s.size();i++){
            if(judge(s,cur,i)){
                string temp(&s[cur],&s[i+1]);
                path.push_back(temp);
                dfs(result,s,path,i+1);
                path.pop_back();  //DFS算法一般不要忘了复位
               
            }
               
                
            }
            
        }

    
    bool judge(string &s, int cur,int i){
        if(cur==i)
        return true;
        while(cur<i){
            if(s[i]!=s[cur])
            return false;
            i--;
            cur++;
        }
        return true;
    }
};

点赞