Question
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s ="aab",
Return
[
["aa","b"],
["a","a","b"]
]
Solution
求解思想用的是DFS,然后需要记录已经判断过是回文的子字符串,具体实现需要慢慢的体会。
Code
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> path;
dfs(0, s, path, res);
return res;
}
void dfs(int index, string s, vector<string> path, vector<vector<string>>& res) {
if (index == s.length()) {
res.push_back(path);
return;
}
for (int i = index; i < s.length(); i++) {
if (isPalindrome(s, index, i)) {
path.push_back(s.substr(index, i - index + 1));
dfs(i + 1, s, path, res);
path.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while (start <= end) {
if (s[start++] != s[end--])
return false;
}
return true;
}
/*
bool isPalindrome(string s, int start, int end) {
if (start >= end)
return true;
if (s[start] != s[end])
return false;
return isPalindrome(s, start++ , end--);
}
*/
};