1. Generate All Partitions + Post-Validation
Intuition
A string of length N has N - 1 potential cut positions. Generate all 2^(N-1) cut subsets. For each partition, verify whether every segment is a palindrome. If all are valid, add partition to result.
When to apply: Baseline comparison to understand total partition space.
Algorithm
- Iterate
maskfrom 0 to(1 << (n - 1)) - 1to define cuts. - Split string according to mask cuts.
- Verify each substring using two-pointer palindrome check.
- If all valid, add to result.
#include <iostream>#include <vector>#include <string> using namespace std; class Solution { bool isPalindrome(const string& s) { int l = 0, r = s.length() - 1; while (l < r) { if (s[l++] != s[r--]) return false; } return true; } public: vector<vector<string>> partition(string s) { int n = s.length(); vector<vector<string>> result; for (int mask = 0; mask < (1 << (n - 1)); mask++) { vector<string> current; int start = 0; bool valid = true; for (int i = 0; i < n - 1; i++) { if (mask & (1 << i)) { string sub = s.substr(start, i - start + 1); if (!isPalindrome(sub)) { valid = false; break; } current.push_back(sub); start = i + 1; } } if (valid) { string sub = s.substr(start); if (isPalindrome(sub)) { current.push_back(sub); result.push_back(current); } } } return result; }}; int main() { Solution sol; auto res = sol.partition("aab"); for (const auto& p : res) { cout << "[ "; for (const string& s : p) cout << s << " "; cout << "] "; } cout << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^N * N^2)— Generates 2^(N-1) partitions, each validated in O(N2) time. - Space complexity:
O(N)— Stores temporary partition segments.