leetcode Palindrome Partitioning II
2014-05-08 10:21
369 查看
题目:
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 =
Return
be produced using 1 cut.
分析:
此题与Palindrome Partitioning的区别是,后者让列出所有的切分情况,对于列出所有情况的题目,一般都是用dfs遍历的方法来做。
而对于与本题类似的题目,只是让找到一种特殊情况,如最小、最大。。。一般都是用动态规划的思路来做。
对于本题的动态规划思路,定义一个数组minCut[],minCut[i]表示字符串s的0-i的最小切分数,
然后遍历j,从0-i, 如果s的字串j-i是回文的话,minCut[i+1] = min(minCut[i+1], minCut[j]+1)
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
1since the palindrome partitioning
["aa","b"]could
be produced using 1 cut.
分析:
此题与Palindrome Partitioning的区别是,后者让列出所有的切分情况,对于列出所有情况的题目,一般都是用dfs遍历的方法来做。
而对于与本题类似的题目,只是让找到一种特殊情况,如最小、最大。。。一般都是用动态规划的思路来做。
对于本题的动态规划思路,定义一个数组minCut[],minCut[i]表示字符串s的0-i的最小切分数,
然后遍历j,从0-i, 如果s的字串j-i是回文的话,minCut[i+1] = min(minCut[i+1], minCut[j]+1)
//动态规划, //minCut[i] 表示0-i的最小切分数 //对于j从0到i,如果j-i的字符串是回文的话,minCut[i+1] = min(minCut[i+1], minCut[j]+1) int minCut(string s) { if(s.size()<=1) return 0; vector<vector<bool> > isPal = isPalindrome3(s); vector<int> minCut(s.length()+1,0); for(int i=0; i<s.length(); i++){ minCut[i+1] = i+1; for(int j=0; j<=i; j++){ if(isPal[j][i]){ minCut[i+1] = min(minCut[i+1], minCut[j]+1); } } } return minCut[s.length()]-1; } //对于isPal[i][j],表示i-j是不是回文 vector<vector<bool> > isPalindrome3(string s){ vector<vector<bool> > isPal(s.length(), vector<bool>(s.length(),false)); for(int i=s.length()-1; i>=0; i--){ for(int j=i; j<s.length(); j++){ if(s[j]==s[i] &&(j-i<2 || isPal[i+1][j-1])){ isPal[i][j] = true; } } } return isPal; }
相关文章推荐
- Palindrome Partitioning I,II[leetcode] DFS以及DP的解法
- 【LeetCode】palindrome-partitioning i&ii
- LeetCode之Palindrome Partitioning II
- LeetCode:Palindrome Partitioning,Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- LeetCode: Palindrome Partitioning II [132]
- leetcode:Palindrome Partitioning II
- LeetCode #132: Palindrome Partitioning II
- Leetcode:Palindrome Partitioning II
- 【LeetCode】Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- LeetCode 132. Palindrome Partitioning II(回文切分)
- LeetCode: Palindrome Partitioning II
- Leetcode 132. Palindrome Partitioning II
- LeetCode 132 Palindrome Partitioning II (动态规划)
- leetcode Palindrome Partitioning I II
- [Leetcode] 132. Palindrome Partitioning II
- LeetCode Palindrome Partitioning II(***)
- [Leetcode][JAVA] Palindrome Partitioning II
- Java for LeetCode 132 Palindrome Partitioning II