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
class Solution {
public:
inline int min(int a, int b){
return a < b ? a : b;
}
int minCut(string s) {
int n = s.size();
vector<vector<bool>> dp(n, vector<bool>(n, false));
for (int i = 0; i < n; i++){
for (int j = 0; j < n - i; j++){
if (s[j] == s[j + i]){
if (i <= 1)
dp[j][j + i] = true;
else
dp[j][j + i] = dp[j + 1][j + i - 1];
}
}
}
vector<int> res(n+1, 0);
res[n] = -1;
for (int i = n - 1; i >= 0; i--){
res[i] = n - i - 1;
for (int j = i; j < n; j++){
if (dp[i][j])
res[i] = min(res[i], 1 + res[j + 1]);
}
}
return res[0];
}
};