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"] ]
由题意得,给定一个字符串,然后把它分成若干段,其中每一段都是回文字符串。
初看题目,感觉无从下手,因为这样的情况特别多。这种情况的题,都可以用深搜来解决,因为深搜会从顶一直搜索到底部,这样就把一整个字符串的一种情况全部记录下来,然后遍历整个深搜树,那么结果就出来了。其中每次搜索下一个字符,都有选或者不选的情况,不选的话,是因为不是回文字符串。由此可见,时间复杂度在O(2^n),代码如下:
Code(LeetCode运行13ms):
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> result;
vector<string> aPath;
DFS(s, aPath, result, 0);
return result;
}
void DFS(string s, vector<string> &aPath, vector<vector<string>> &result, int start) {
if (start == s.size()) {
result.push_back(aPath);
return;
}
for (int i = start; i < s.size(); i++) {
if (isPalindrome(s, start, i)) {
aPath.push_back(s.substr(start, i - start + 1));
DFS(s, aPath, result, i + 1);
aPath.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while (start < end && s[start] == s[end]) {
start++;
end--;
}
return start >= end;
}
};