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"] ]
分割字符串s使得每一段都是回文串,找出所有这样的组合。
dfs遍历。
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string> > ans;
if (s.length() == 0) return ans;
vector<string> path;
dfs(ans, s, path, 0);
return ans;
}
void dfs(vector<vector<string> >& ans, string s, vector<string> path, int loc) {
if (loc == s.length()) {
ans.push_back(path);
return;
}
for (int i = loc; i < s.length(); ++i) {
if (isPartition(s, loc, i)) {
path.push_back(s.substr(loc, i - loc + 1));
dfs(ans, s, path, i+1);
path.pop_back();
}
}
}
bool isPartition(string s, int st, int ed) {
while (st < ed) {
if (s[st] != s[ed]) return false;
st++;
ed--;
}
return true;
}
};