C++ simple recursive solution


  • 2
    D
    class Solution {
    public:
        bool isPalindrome(string &str, int s, int e) {
            while (s < e) {
                if (str[s] != str[e])
                    return false;
                s++; e--;
            }
            return true;
        }
        
        vector<vector<string>> partition(string s, int i) {
            vector<vector<string>> result;
            for (int j = i; j < s.length(); ++j) {
                if (isPalindrome(s, i, j)) {
                    if (j + 1 < s.length()) {
                        vector<vector<string>> result2 = partition(s, j+1);
                        for (int k = 0; k < result2.size(); ++k) {
                            result.push_back(vector<string>(result2[k].size() + 1, ""));
                            result.back()[0] = s.substr(i, j-i+1);
                            copy(result2[k].begin(), result2[k].end(), result.back().begin() + 1);
                        }
                    } else {
                        result.push_back(vector<string>(1, s.substr(i, j-i+1)));
                    }
                }
            }
            return result;
        }
    
        vector<vector<string>> partition(string s) {
            return partition(s, 0);
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.