Problem overview
The method partition gets a string s of 1 to 12 lowercase letters and returns every way to cut it into pieces that are all palindromes. A palindrome reads the same backwards, and a single letter is one. The pieces keep the letters in order and every letter lands in exactly one piece. A way is a vector<string>, and the answer is a vector<vector<string>> of ways.
The ways must come in a fixed order: by first piece, shortest first, then by second piece, and so on. That is the order produced by always trying the shortest next piece first.
For "noon" the answer is [["n","o","o","n"],["n","oo","n"],["noon"]]. For "cat" it is [["c","a","t"]], since "ca", "at" and "cat" are not palindromes. For "bbb" it is [["b","b","b"],["b","bb"],["bb","b"],["bbb"]].
Approach: choose the first piece, then cut the rest
Every valid way starts with a first piece that begins at the first letter and is a palindrome. Try each possible length for it. For each palindromic first piece, the rest of the string must be cut the same way, which is a smaller version of the same problem. When the cut reaches the end of the string, the pieces chosen so far are one complete way.
That is backtracking: add a piece, recurse, then remove the piece and try the next length. The order falls out of the loop. Trying end from start upwards tries the shortest piece first, and the recursion explores everything after that piece before moving on to a longer one.
Between every two neighbouring letters you either cut or you don't, so there are at most 2^(n-1) ways. Checking a piece and copying a finished way each take O(n), which gives the lesson's O(n * 2^n) bound. The worst input is a string of one repeated letter: twelve a's have 2048 ways, while twelve different letters have only one.
A trace of "noon": the first piece "n" leaves "oon". There, "o" leaves "on", where "o" leaves "n", which gives the way n, o, o, n. Back at "on", "on" is not a palindrome, so the loop ends. Back at "oon", the piece "oo" leaves "n", which gives n, oo, n. The piece "oon" is not a palindrome. Back at the top, the first pieces "no" and "noo" are not palindromes and are skipped. Finally "noon" is a palindrome and uses the whole string, giving noon.
Step by step
- Create
result, avector<vector<string>>that collects the finished ways. - Create
current, avector<string>holding the pieces of the way being built. - Start the search:
backtrack(s, 0, current, result). The 0 means no letter is in a piece yet. - Return
result. - Declare
backtrack. It returnsvoidand takess,start(the first letter not yet in a piece),currentandresult. - Base case. If
start == s.size(), every letter is in a piece. - Save a copy of
currentwithpush_backand return. - Loop over the piece's end, from
startup to the last index. - Test the piece from
starttoendwithisPalindrome. - Take the piece:
s.substr(start, end - start + 1)goes ontocurrent. - Recurse from
end + 1. - Undo the choice with
pop_back(), so the loop can try a longer piece. - Write
isPalindrome. It takess,startandend. Two indexes,leftandright, walk towards each other. - Compare in pairs. While
left < right, a differing pair returnsfalse; otherwise both indexes move inward. - Return
truewhen the loop finishes. A one-letter piece never enters the loop, so it is a palindrome.
The solution in C++
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> current;
backtrack(s, 0, current, result);
return result;
}
void backtrack(string& s, int start, vector<string>& current, vector<vector<string>>& result) {
if (start == s.size()) {
result.push_back(current);
return;
}
for (int end = start; end < s.size(); end++) {
if (isPalindrome(s, start, end)) {
current.push_back(s.substr(start, end - start + 1));
backtrack(s, end + 1, current, result);
current.pop_back();
}
}
}
bool isPalindrome(string& s, int start, int end) {
int left = start;
int right = end;
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
};
The C++ details worth a closer look:
substr(pos, length), not two positions. The second argument is a length, which is why the piece usesend - start + 1. Passingendwould take too many letters wheneverstartis above 0.push_back(current)stores a copy.currentkeeps changing as the search goes on, but each saved way is independent, so laterpop_back()calls do not damage it.- References as parameters.
s,currentandresultare passed with&. Without it each call would copy the string and the vectors, and changes tocurrentandresultwould not reach the caller. - Signed and unsigned.
start == s.size()andend < s.size()compare anintwith an unsignedsize_t. The indexes here are never negative, so the comparisons are correct, though a compiler may warn about them.
Complexity
Time is O(n * 2^n): up to 2^(n-1) ways, each costing O(n) to check and copy. Besides the answer, the extra space is O(n): the pieces in current and the open calls, at most n deep.
Edge cases and common mistakes
- Forgetting
pop_back(). Pieces would pile up incurrent, and the later ways would contain pieces from earlier choices. - Wrong palindrome bounds.
isPalindrometakes inclusivestartandendindexes. Passingend + 1checks one letter too many. - Recursing from
endinstead ofend + 1. The last letter would be used twice, and the search would not stop. - One letter. For
"a"the answer is[["a"]]. - Several letters but one way. A string with no palindromes longer than one letter, such as
"cat", has exactly one way: every letter on its own.
Testing
The function printed these results:
| s | Result |
|---|---|
"noon" | [["n","o","o","n"],["n","oo","n"],["noon"]] |
"aab" | [["a","a","b"],["aa","b"]] |
"a" | [["a"]] |
"aaaaaaaaaaaa" | 2048 ways |
"abcdefghijkl" | 1 way |
