131. Palindrome Partitioning

131. Palindrome Partitioning

Description

Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Example 1:

1
2
Input: s = "aab"
Output: [["a","a","b"],["aa","b"]]

Example 2:

1
2
Input: s = "a"
Output: [["a"]]

Constraints:

  • 1 <= s.length <= 16
  • s contains only lowercase English letters.

Hints/Notes

Solution

Language: C++

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
class Solution {
public:
vector<string> path;
vector<vector<string>> res;

vector<vector<string>> partition(string s) {
dfs(0, s);
return res;
}

void dfs(int index, string& s) {
if (index == s.size()) {
res.push_back(path);
return;
}

for (int i = index + 1; i <= s.size(); i++) {
if (isPalindrome(s, index, i - 1)) {
path.push_back(s.substr(index, i - index));
dfs(i, s);
path.pop_back();
}
}
}

bool isPalindrome(string& s, int l, int r) {
while (l < r) {
if (s[l] != s[r]) {
return false;
}
l++;
r--;
}
return true;
}
};