您的位置:首页 > 其它

[Leetcode]Palindrome Partitioning II

2015-10-25 18:13 357 查看
Given a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s =
"aab"
,

Return
1
since the palindrome partitioning
["aa","b"]
could be produced using 1 cut.

Have you met this question in a real interview?

class Solution {
public:
/*algorithm: backtracking
backtrack all possible combination, from len to 1
*/
bool isPalindrome(string &s){
for(int i = 0,j = (int)s.size() - 1;i < j;i++,j--){
if(s[i] != s[j])return false;
}
return true;
}
void dfs(string s,vector<string>&path,int &minCnt){
if(s.empty()){
if(path.size() < (minCnt + 1))
minCnt = (int)path.size() - 1;
return;
}
for(int len = s.size();len > 0;len--){
if(path.size() >= (minCnt+1))break;
string sub = s.substr(0,len);
if(isPalindrome(sub)){
path.push_back(sub);
dfs(s.substr(len),path,minCnt);
path.pop_back();
}
}
}
int minCut(string s) {
vector<string>path;
int minCnt = s.size();
dfs(s,path,minCnt);
return minCnt;
}
};
class Solution {
public:
/*algorithm: DP
use plain to track the palindrome
plain(i,i)=1
plain(i,i+1)=1 if(s[i]==s[i+1])
plain(i,j) = 1  if(plain(i+1,j-1) && s[i]==s[j]
dp[i] : minimum cuts from i to end.
*/
int minCut(string s) { //abba
if (s.empty()) return 0;
int len = s.size();
vector<int>dp(len+1,0);
vector<vector<int> >palin(len,vector<int>(len,0));

for (int i = len - 1; i >= 0; i--) {
dp[i] = len - i;
for (int j = i; j < len; j++) {
if ((s[i] == s[j] && (j - i) < 2) || (s[i] == s[j] && palin[i + 1][j - 1])) {
palin[i][j] = 1;
dp[i] = min(dp[i], dp[j + 1] + 1);
}
}
}
return dp[0] - 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 算法