题目要求:
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 res = 1 << 30;
int cut_num = 0;
DFS(s, 0, cut_num, res);
return res - 1;
}
void DFS(const string& str, int start, int& cut_num, int &res)
{
if (start == str.size()) {
if(cut_num < res)
res = cut_num;
return;
}
if(cut_num > res)
return;
for (int i = str.size() - 1; i >= start; --i) {
if(IsPalindrome(str, start, i))
{
++cut_num;
DFS(str, i + 1, cut_num, res);
--cut_num;
}
}
}
bool IsPalindrome(const string& str, int start, int end)
{
while (start < end) {
if(str[start] != str[end])
return false;
++start;
--end;
}
return true;
}
};
其实,凡是要求最值得 多半是动态规划。设dp[i,j]表示 从i到j可以分成回文子串的最少段数,很容易得到 :
dp[i,j] = min(dp[i,k] + dp[k + 1, j]) i <= k <= j, 将其转换成一维动态规划.
dp[i]代表从i开始到n得最小cut数。 dp[i] = min(1 + dp[j + 1]) i <= j < n.
另外,在判断字符串是否是回文的时候 每次都通过扫描比较也比较浪费时间,可以用一个二维数组来保存已经计算过的结果,其实也是一个动态规划的过程,用is_palindrome[i][j]保存i到j之间的字符串是否是回文。初始化的时候:is_palindrome[i][j] = true , i == j;
is_palindrome[i][j] = (str[i] == str[j]) && is_palindrome[i + 1][j - 1];
动态规划代码:
int minCut(string s) {
int len = s.size();
int dp[len + 1];
for (size_t i = 0; i <= len; ++i) {//初始化dp数组,初始值是将每个字母都切开
dp[i] = len - i;
}
bool is_palindrome[len][len];
memset(is_palindrome, false, sizeof(is_palindrome));
for (int i = len - 1; i >= 0; --i) {
for (int j = i; j < len; ++j) {
if(s[i] == s[j] && ((j - i) < 2 ||//如果(j - i) < 2 说明只有一个字符肯定是回文
is_palindrome[i + 1][j - 1]))
{
is_palindrome[i][j] = true;
dp[i] = min(dp[i], dp[j + 1] + 1);
}
}
}
return dp[0] - 1;
}