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.
从后往前构造二维数组isPalin,用于存储已经确定的回文子串。isPalin[i][j]==true代表s[i,...,j]是回文串。
在构造isPalin的同时使用动态规划计算从后往前的最小切分数,记录在min数组中。min[i]代表s[i,...,n-1]的最小切分数。
(上述两步分开做会使得代价翻倍,容易TLE)
关键步骤:
1、min[i]初始化为min[i+1]+1,即初始化s[i]与s[i+1]之间需要切一刀。这里考虑边界问题,因此min数组设为n+1长度。
2、从i到n-1中间如果存在位置j,同时满足:(1)s[i,...,j]为回文串;(2)1+min[j+1] < min[i]。
那么min[i]=1+min[j+1],也就是说一刀切在j的后面比切在i的后面要好。
class Solution { public: int minCut(string s) { int n = s.size(); vector<vector<bool> > isPalin(n, vector<bool>(n, false)); vector<int> min(n+1, -1); //min cut from end for(int i = 0; i < n; i ++) { isPalin[i][i] = true; } for(int i = n-1; i >= 0; i --) { min[i] = min[i+1] + 1; for(int j = i+1; j < n; j ++) { if(s[i] == s[j]) { if(j == i+1 || isPalin[i+1][j-1] == true) { isPalin[i][j] = true; if(j == n-1) min[i] = 0; else if(min[i] > min[j+1]+1) min[i] = min[j+1] + 1; } } } } return min[0]; } };