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:
Input: s = “aab” Output: [[“a”,“a”,“b”],[“aa”,“b”]]
Example 2:
Input: s = “a” Output: “a”
Constraints:
1 <= s.length <= 16
s
contains only lowercase English letters.
Code
Time Complexity: , Space Complexity:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
if(s.empty()) return res;
vector<string> cur;
dfs(0, s, cur, res);
return res;
}
void dfs(int index, string& s, vector<string>& cur, vector<vector<string>>& res) {
if(index == s.length()) {
res.push_back(cur);
return;
}
for(int i = index; i < s.length(); i++) {
if(isPalindrome(s, index, i)) {
cur.push_back(s.substr(index, i - index + 1));
dfs(i + 1, s, cur, res);
cur.pop_back();
}
}
}
bool isPalindrome(const string& s, int l, int r) {
while(l <= r) {
if(s[l++] != s[r--])
return false;
}
return true;
}
};