您的位置:首页 > 其它

[leetcode][DP] Palindrome Partitioning II

2015-07-01 11:12 531 查看
题目;

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.
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<int> table2(n);//table2[i]表示从s[i]到s[n-1]分成palindrom最少需要切几刀
vector<bool> dummy(n, false);
vector<vector<bool> > table1(n);//table[i][j]表示s[i]...s[j]能否构成回文
for (int i = 0; i < n; ++i){
table2[i] = n - i - 1;
}
for (int i = 0; i < n; ++i){
table1[i] = dummy;
}
for (int i = n - 2; i >= 0; --i){
for (int j = i; j < n; ++j){
if (i == j || s[i] == s[j] && (j == i + 1 || table1[i + 1][j - 1])){
table1[i][j] = true;
if (j == n - 1) table2[i] = 0;
else table2[i] = table2[j + 1] + 1 < table2[i] ? table2[j + 1] + 1 : table2[i];
}
}
}
return table2[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: