链接: https://oj.leetcode.com/problems/palindrome-partitioning/
dp+dfs
求字符串s的所有分割,使得每一个子串都是回文字符串.
dp数组用来储存s[i]~s[j]是否为回文串.由于二维数组传递不方便,所以用dp[i]来计算 :dp[i][j] ->dp[i*n+j]
if s[j]==s[j+i]&& dp[j+1][j+i-1]==true ;->dp[j][j+i]=true;
dfs(i,...) :求s[i~s.length()]的所有符合条件的分割.
class Solution { public: void dfs(int i,string s,int n,bool dp[] ,vector<string> &vet,vector<vector<string> > &ans) { if(i==n) { ans.push_back(vet); return ; } for(int j=i; j<n; j++) { if(dp[i*n+j]) { vet.push_back(s.substr(i,j-i+1)); dfs(j+1,s,n,dp,vet,ans); vet.pop_back(); } } } vector<vector<string> >partition(string s) { int n=s.size(); bool *dp=new bool[n*n]; vector<vector<string> > ans; vector<string> vet; if(n==0) return ans; for(int i = 0; i < n*n; i ++) dp[i] = false; for(int i = 0; i < n; i++) { dp[i*n+i] = true; } for(int i = 1; i < n; i ++) { for(int j = 0; j+i < n; j ++) { if(s[j] == s[j+i] && (dp[(j+1)*n+j+i-1]||i==1)) dp[j*n+j+i] = true; } } dfs(0,s,n,dp,vet,ans); return ans; } };