题目:
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.
Example:
Input: "aab" Output: 1 Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
代码:
方法一——在palindrome Partitioning的基础上,但是超时了:
class Solution {
public:
void helper(vector <vector<bool>>& b, string& s, int start, vector<string>& v, int& min) {
if (start >= s.size()) {
if (v.size()-1 < min) { min = v.size()-1; }
return;
}
for (int i = start; i < s.size(); i++) {
if(v.size()>min)return;
if (b[start][i]) {
v.push_back(s.substr(start, i - start + 1));
helper(b, s, i + 1, v, min);
v.pop_back();
}
}
}
int minCut(string s) {
int len = s.length();
vector<vector<bool>> b(len, vector<bool>(len, false));
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
if (s[i] == s[j] && (i - j <= 2 || b[j + 1][i - 1])) {
b[j][i] = true;
}
}
}
int res = INT_MAX;
vector<string> v;
helper(b, s, 0, v, res);
return res;
}
};
方法二——简单点的动态规划:
class Solution {
public:
int minCut(string s) {
if (s.empty()) return 0;
int n = s.size();
vector<vector<bool>> p(n, vector<bool>(n));
vector<int> dp(n);
for (int i = 0; i < n; ++i) {
dp[i] = i;
for (int j = 0; j <= i; ++j) {
if (s[i] == s[j] && (i - j < 2 || p[j + 1][i - 1])) {
p[j][i] = true;
dp[i] = (j == 0) ? 0 : min(dp[i], dp[j - 1] + 1);
}
}
}
return dp[n - 1];
}
};