标签:leetcode 面试 algorithm 回文划分 palindrome partition
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] = min(dp[i], dp[j+1]+1)), i<=j<n;
dp[i] : 表示从 i 到串尾的最小划分数。
class Solution { public: int minCut(string s) { int n = s.size(); vector<int> dp(n+1, 0); vector<vector<int> > imap(n+1, vector<int>(n+1, 0)); for(int i=n-1;i>=0; --i){ dp[i] = n-i; for(int j=i; j<n; ++j){ if(s[i] != s[j]) continue; if(j-i<2 || imap[i+1][j-1]==1){ imap[i][j] = 1; dp[i] = min(dp[i], dp[j+1] +1); } } } return dp[0]-1; } };
[LeetCode] Palindrome Partitioning II [12],布布扣,bubuko.com
[LeetCode] Palindrome Partitioning II [12]
标签:leetcode 面试 algorithm 回文划分 palindrome partition
原文地址:http://blog.csdn.net/swagle/article/details/28904745