problem:https://leetcode.com/problems/palindrome-partitioning-ii/
爬台阶类型问题。先计算出所有可能的回文串,dp[ i ] 代表前 i 个字符的最小划分,找到以 i 结尾的所有回文串,取划分最小的那个作为结果。
class Solution { public: int minCut(string s) { int n = s.size(); vector<vector<bool>> palindrome(n, vector<bool>(n, false)); for(int i = 0;i < n;i++) { palindrome[i][i] = true; for(int times = 0; times < 2; times++) { int j; if(times == 0) j = i - 1; else j = i; int k = i + 1; while(j >= 0 && k < n) { if(s[j] == s[k]) { palindrome[j][k] = true; j--; k++; } else break; } } } vector<int> dp(n + 1); dp[0] = -1; for(int i = 0;i < n; i++) { dp[i + 1] = i; for(int j = 0;j <= i; j++) { if(palindrome[j][i]) { dp[i + 1] = min(dp[i + 1], dp[j] + 1); } } } return dp[n]; } };
[动态规划 leetcode 132 Palindrome Partitioning II
原文:https://www.cnblogs.com/fish1996/p/11330148.html