[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 =
Return
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;
}
};
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s =
"aab",
Return
1since 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; } };
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例