-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0131-palindrome-partitioning.cpp
44 lines (41 loc) · 1.23 KB
/
0131-palindrome-partitioning.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
Given a string, partition such that every substring is a palindrome, return all possible ones
Ex. s = "aab" -> [["a","a","b"],["aa","b"]], s = "a" -> [["a"]]
Generate all possible substrings at idx, if palindrome potential candidate, backtrack after
Time: O(n x 2^n)
Space: O(n)
*/
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<string> curr;
vector<vector<string>> result;
dfs(s, 0, curr, result);
return result;
}
private:
void dfs(string s, int start, vector<string>& curr, vector<vector<string>>& result) {
if (start == s.size()) {
result.push_back(curr);
return;
}
for (int i = start; i < s.size(); i++) {
if (isPalindrome(s, start, i)) {
string str = s.substr(start, i - start + 1);
curr.push_back(str);
dfs(s, i + 1, curr, result);
curr.pop_back();
}
}
}
bool isPalindrome(string s, int left, int right) {
while (left < right) {
if (s[left] != s[right]) {
return false;
}
left++;
right--;
}
return true;
}
};