leetcode: Palindrome Partitioning II解法
来源:互联网 发布:淘宝热销商品 编辑:程序博客网 时间:2024/06/05 08:04
题目如下:
Given a string s, partition s such thatevery substring of the partition is a palindrome.
Return the minimum cuts needed for apalindrome partitioning of s.
For example, given s = "aab",
Return 1 since thepalindrome partitioning ["aa","b"] could be produced using 1 cut.
这个题目的解法是动态规划。首先用b这个矩阵来代表s[i]-s[j]是否是palindrome。b[i][j]==true 意思是s[i]到s[j]事palindrome。
之后用result来动态计算s[0]-s[j]的最小cut,每一次看判断最小值。
class Solution {public: int minCut(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int len=s.length(); if(len<1) return 0; vector<bool> temp(len,false); vector<vector<bool>> b(len,temp); int i; for(i=0;i<len;i++) { b[i][i]=true; } for(i=0;i<len-1;i++) { if(s[i]==s[i+1]) b[i][i+1]=true; } int l; for(l=3;l<=len;l++) { for(i=0;i<=len-l;i++) { int j=i+l-1; if(s[i]==s[j] && b[i+1][j-1]) b[i][j]=true; } } int min=helper(b,s); return min; } int helper(vector<vector<bool>>& b, string s) { vector<int> result(s.length(),0); result[0]=0; for(int j=0; j<s.length(); j++) { int min=j; if(b[0][j]) result[j]=0; else { for(int i=1;i<=j;i++) { if(b[i][j] && result[i-1]+1<=min) min=result[i-1]+1; } result[j]=min; } } return result[s.length()-1]; }};
- leetcode: Palindrome Partitioning II解法
- Palindrome Partitioning I,II[leetcode] DFS以及DP的解法
- LeetCode : Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- leetcode:Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- leetcode - Palindrome Partitioning II
- [LeetCode]Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- leetcode Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- LeetCode - Palindrome Partitioning II
- [Leetcode]Palindrome Partitioning II
- 【leetcode】Palindrome Partitioning II
- LeetCode Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- C程序设计课程-2012电子信息第五次上机实验
- silverlight实现页面跳转,保存上次的页面访问的状态,像手机应用一样
- 在WinXP上编译Doom3源码提示
- DOOM3 源码分析笔记(1)
- 第九章 OGRE中的整个流程
- leetcode: Palindrome Partitioning II解法
- 自动化管理SSH密匙的建议
- Compiling newest Boost_1_53_0 with VS2008
- IOS开发网络加载图片缓存策略之──ASIDownloadCache缓存策略
- [Latex][beamer]PGF and TiKz中演示文字沿路径移动的动画
- [Latex][beamer]PGF and TiKz中如何定位曲线路径上的任一点
- Codeforces Round #179 (Div. 2) C Greg and Array
- 【黑马程序员】ADO.NET访问EXCEL(学习笔记)
- XDU 1010