[LeetCode-132] Palindrome Partitioning II
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,第一个获取全部索引i到j是否回文,第二个可以理解为在s[i]到s[j-1]的基础上新增s[j]、s[j]历遍所有组合找到min_cut。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution { 2 public: 3 int minCut(string s) { 4 int slen = s.length(); 5 vector<int> min_cut(slen, INT_MAX); 6 vector<vector<bool> > is_palin(slen, vector<bool>(slen, false)); 7 8 // get is palin matrix 9 for (int j = 0; j < slen; ++j) { 10 for (int i = 0; i <= j; ++i) { 11 if (i == j) { 12 is_palin[i][j] = true; 13 } else if (i + 1 == j) { 14 is_palin[i][j] = s.at(i) == s.at(j); 15 } else { 16 is_palin[i][j] = is_palin[i + 1][j - 1] && s.at(i) == s.at(j); 17 } 18 } 19 } 20 21 // get min cut 22 int tmp = INT_MAX; 23 for (int j = 0; j < slen; ++j) { 24 if (is_palin[0][j]) { 25 min_cut[j] = 0; 26 } 27 else { 28 tmp = j; 29 for (int i = 1; i <= j; ++i) { 30 if (is_palin[i][j]) { 31 tmp = min(tmp, min_cut[i - 1] + 1); 32 } 33 } 34 min_cut[j] = tmp; 35 } 36 } 37 38 return min_cut[slen - 1]; 39 } 40 };