Title

# 最小回文分割 | DFS生成回文

"aab"

1


class Solution {
public:
/**
*
* @param s string字符串
* @return int整型
*/
int minCut(string s) {
int n = s.size();
if (n<=1) return 0;

int dp[n+1];
memset(dp,0x3f,sizeof dp);
dp[0]=-1;
for(int i=0;i<n;++i) {
for(int len=0;i-len>=0 && i+len<n && s[i-len]==s[i+len];++len) {
dp[i+len+1] = min(dp[i+len+1],dp[i-len]+1);
}
for(int len=0;i-len>=0 && i+len+1<n&& s[i-len]==s[i+len+1]; ++len) {
dp[i+len+2] = min(dp[i+len+2],dp[i-len]+1);
}
}
return dp[n];
}
bool isPalid(string &s,int i,int j) {
while(i<j) if(s[i++]!=s[j--]) return false;
return true;
}
};



"dde"

[["d","d","e"],["dd","e"]]



class Solution {
public:
/**
*
* @param s string字符串
* @return string字符串vector<vector<>>
*/
vector<vector<string> > partition(string s) {
// write code here
vector<vector<string>> res;
vector<string> cur;
dfs(res,cur,s);
return res;

}
void dfs(vector<vector<string>> &res,vector<string>&cur,string& s) {
if(s.size()<1) {
res.push_back(cur);
return;
}
for(int len=1;len<=s.size();++len) {
string sub = s.substr(0,len);
if(isPali(sub,0,len-1)) {
cur.push_back(sub);
string p = s.substr(len);
dfs(res,cur,p);
cur.pop_back();
}
}
}

bool isPali(string&s,int l,int r) {
if(l==r) return true;
while(l<r )if(s[l++]!=s[r--]) return false;
return true;
}
};


posted @ 2021-01-25 12:41  .geek  阅读(93)  评论(0编辑  收藏  举报