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"] ]
Have you met this question in a real interview?
class Solution {
public:
/*algorithm: DFS
*/
bool isPalindrome(string &s){//"aab"
for(int i = 0,j = (int)s.size() - 1;i < j;i++,j--){
if(s[i] != s[j])return false;
}
return true;
}
void dfs(vector<vector<string>>&result,vector<string>&path,string s){
if(s.empty()){
result.push_back(path);
return;
}
for(int i = 1;i <= s.size();i++){
string sub = s.substr(0,i);
if(!isPalindrome(sub))continue;
path.push_back(sub);
dfs(result,path,s.substr(i));
path.pop_back();
}
}
vector<vector<string>> partition(string s) {
vector<vector<string>>result;
vector<string>path;
dfs(result,path,s);
return result;
}
};