题目:https://oj.leetcode.com/problems/palindrome-partitioning-ii/
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.
可以用DP的思路解这道题。
定义二维数组dp[i][j]记录从i到j的子串是否是回文;一维数组cutNum[i]记录从i开始到字符串结尾的子串的最小分割次数。先将cotNum初始化为每个子串的最大分割次数s.size() - i;(实际次数为cutNum[i] - 1)
动规过程中的动态转移方程是:cutNum[i] = min(cutNum[i],cutNum[j + 1] + 1)前提是子串i到j是回文。
AC代码:
class Solution {
public:
int minCut(string s) {
int len = s.size();
//dp二维数组记录字符串从i到j是否是回文
vector<vector<bool> > dp(len,vector<bool>(len,false));
//cutNum[i]记录从i开始到字符串结尾的子串的最小分割次数
vector<int> cutNum(len + 1,0);
for(int i = len - 1;i >= 0;i--){
//先将最小切割次数初始化为len - i
cutNum[i] = len - i;
for(int j = i;j < len;j++){
//如果从i到j的子串是回文则s[i]肯定等于s[j]
if(s[i] == s[j]){
//s[i] == s[j]的情况下,如果j - i < 2或者从i+1到j-1的子串是回文则从i到j的子串是回文
if(j - i < 2 || dp[i + 1][j - 1]){
dp[i][j] = true;
//则从i开始到字符串结尾的子串用两种切割情况:
//切割出从i到j的子串或者不切割,最小切割次数取其中比较小的值
cutNum[i] = cutNum[i] < (cutNum[j + 1] + 1)?cutNum[i] : (cutNum[j + 1] + 1);
}
}
}
}
return cutNum[0] - 1;
}
};