Palindrome Partitioning

题目大意:给定一个字符串,要求你对其进行切割,保证切割后每个子字符串都是回文串,要你求所有满足条件的集合

解题思路:递归,为了避免重复计算,用isPalindrome[i][j]表示str[i][j]是否是回文串,为0表示不是,1表示是,-1表示还没有遍历进行判断


class Solution {
public:
    vector> partition(string s) {
        vector > result;
        if(s.empty()) {
            return result;
        }
        vector > isPalindrome(s.size(), vector(s.size(), -1));
        vector strs;
        for(int i = 0; i < s.size(); i++) {
            isPalindrome[i][i] = 1;
        }
        partitionAssist(s, 0, result, strs, isPalindrome);
        return result;
    }
private:
    void partitionAssist(const string &s, int startIndex, vector > &result, vector &strs, vector > &isPalindrome) {
        if(startIndex >= s.size()) {
            if(!strs.empty()) {
                result.push_back(strs);
            }
        }

        for(int len = 1; startIndex + len <= s.size(); len++) {
            if(isPalindrome[startIndex][startIndex + len - 1] == 0) {
                continue;
            } else if(isPalindrome[startIndex][startIndex + len - 1] == 1) {
                strs.push_back(s.substr(startIndex, len));
                partitionAssist(s, startIndex + len, result, strs, isPalindrome);
                strs.pop_back();
            } else {
                if(s[startIndex] == s[startIndex + len - 1] && (len == 2 || isPalindrome[startIndex + 1][startIndex + len - 2] == 1)) {
                    isPalindrome[startIndex][startIndex + len - 1] = 1;
                    strs.push_back(s.substr(startIndex, len));
                    partitionAssist(s, startIndex + len, result, strs, isPalindrome);
                    strs.pop_back();
                } else {
                    isPalindrome[startIndex][startIndex + len - 1] = 0;
                }
            }
        }
    }
};




你可能感兴趣的:(leetcode)