[leetcode]131. Palindrome Partitioning

[leetcode]131. Palindrome Partitioning


Analysis

Happy girls day—— [每天刷题并不难0.0]

Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
[leetcode]131. Palindrome Partitioning_第1张图片

Explanation:

Solved by recursive. Go through the string s, see if s[0, i] is palindrome . If it is, recursive call DFS(i+1) to check if the rest of s is palindrome.

Implement

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

你可能感兴趣的:(LeetCode,Medium,recursive)