Palindrome Partitioning II
2013-04-09 22:40
274 查看
设dp[i]表示从0到i位置最少需要切割的刀数。则这道题目的状态转移方程为:dp[i]=min(dp[j])+1,其中j>=0&&j<i&&p[j+1][i]是回文串,p[i][j]用来表示i-j之间是否是回文串,这个串可以通过p数组来直接访问。
需要注意的是:提交到leetcode的时候需要用向量,将p和dp替换成向量,否则会Runtime Error.
需要注意的是:提交到leetcode的时候需要用向量,将p和dp替换成向量,否则会Runtime Error.
#include<stdio.h> #include<stdlib.h> #include<iostream> #include<iomanip> using namespace std; int p[1600][1600]; int dp[1600]; int minCut(string s) { memset(p,0,sizeof(p)); memset(dp,0,sizeof(dp)); int len=s.length(),i,j; for(i=0;i<len;i++) p[i][i]=1; for(i=0;i+1<len;i++) if(s[i]==s[i+1]) p[i][i+1]=1; for(i=3;i<=len;i++){ for(j=0;j+i-1<len;j++) if(s[j]==s[j+i-1]&&p[j+1][j+i-2]==1) p[j][j+i-1]=1; } int tmp; for(i=1;i<len;i++){ if(p[0][i]==1){ dp[i]=0; continue; } tmp=0x7fffffff; for(j=0;j<i;j++){ if(p[j+1][i]==1){ if(tmp>dp[j]+1) tmp=dp[j]+1; } } dp[i]=tmp; } return dp[len-1]; } int main(){ cout<<minCut(tmp); system("pause"); return 0; }
相关文章推荐
- leetcode Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- Palindrome Partitioning II
- Leetcode: Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II
- Palindrome Partitioning II(找给定字符串分割次数获取回文字串, 动态规划)
- Leetcode: Palindrome Partitioning II
- **Palindrome Partitioning II
- Palindrome Partitioning II - Leetcode
- Palindrome Partitioning II
- 最小回文分割数 Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- Leetcode_palindrome-partitioning-ii
- [leetcode]Palindrome Partitioning II
- LeetCode Palindrome Partitioning II(***)
- Palindrome Partitioning II
- [LeetCode] Palindrome Partitioning II
- Palindrome Partitioning II
- [leetcode]Palindrome Partitioning II