Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
Example:
Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]
解法1 DFS,回溯
利用DFS,递归函数helper,从start开始,搜索每个子字符串,如果是回文就加入到out中,递归下一个位置start+1;
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> out;
helper(res,out,0,s);
return res;
}
void helper(vector<vector<string>>& res, vector<string>& out, int start, string s){
if(start == s.size()){
res.push_back(out);
return ;
}
for(int i=start;i<s.size();i++){
if (!isPalindrome(s, start, i)) continue;
out.push_back(s.substr(start, i - start + 1));
helper(res,out,i+1,s);
out.pop_back();
}
}
bool isPalindrome(string s, int start, int end){
while (start < end) {
if (s[start] != s[end]) return false;
++start; --end;
}
return true;
}
};
解法2:dp+DFS
利用一个dp二维数组表示是否为回文子串,不用调用回文判断函数,降低时间复杂度。
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
vector<string> out;
int n = s.size();
vector<vector<bool>> dp(n,vector<bool>(n));
for(int i=0;i<n;i++){
for(int j = 0; j <= i; j ++)
if(s[i]== s[j] && (i-j<=2 || dp[j+1][i-1]))
dp[j][i] = 1;
}
helper(res,out,dp,0,s);
return res;
}
void helper(vector<vector<string>>& res, vector<string>& out, vector<vector<bool>>& dp, int start, string s){
if(start == s.size()){
res.push_back(out);
return ;
}
for(int i=start;i<s.size();i++){
if (!dp[start][i]) continue;
out.push_back(s.substr(start, i - start + 1));
helper(res,out,dp,i+1,s);
out.pop_back();
}
}
};
参考
https://www.cnblogs.com/grandyang/p/4270008.html