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"] ]
思路:
这一题为什么没有想到深搜呢?一般要把所有答案都遍历一边的题目都需要深搜。
回顾题目word break 2.
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
见http://blog.csdn.net/kiki_yu/article/details/24603089
代码:
class Solution {
public:
vector<vector<string> > partition(string s) {
vector<vector<string> > ans;
vector<string> cur;
dfs(0, s.length(), s, cur, ans);
return ans;
}
void dfs(int start, int depth, string s, vector<string> & cur, vector<vector<string> > &ans) {
if (start == depth) {
ans.push_back(cur);
return;
}
for (int i = start; i < depth; i++) {
if (isPalindrome(s, start, i)) {
cur.push_back(s.substr(start, i - start + 1));
dfs(i + 1, depth, s, cur, ans);
cur.pop_back();
}
}
}
bool isPalindrome(string s, int b, int e) {
for (int i = b, j = e; i < j; i++, j--) {
if (s[i] != s[j])
return false;
}
return true;
}
};