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.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

class Solution {
public:
    bool isPalindrome(string &s, int left, int right)
    {
        while (left < right)
        {
            if (s[left] != s[right])
            {
                return false;
            }
            left++;
            right--;
        }

        return true;
    }

    void visit(string &s, int len, int begin, vector<string> &temp, vector<vector<string> > &result)
    {
        if (begin >= len)
        {
            result.push_back(temp);
            return;
        }

        for (int i = begin; i < len; i++)
        {
            if (isPalindrome(s, begin, i))
            {
                temp.push_back(s.substr(begin, i-begin+1));
                visit(s, len, i+1, temp, result);
                temp.pop_back();
            }
        }
    }
    
    vector<vector<string>> partition(string s) {
        vector<vector<string> > result;
        vector<string> temp;
        int len = s.length();
        if (len < 1)
        {
            return result;
        }

        visit(s, len, 0, temp, result);

        return result;
    }
};


你可能感兴趣的:(Palindrome Partitioning)