Palindrome Partitioning II
来源:互联网 发布:热风淘宝商城旗舰店 编辑:程序博客网 时间:2024/05/16 07:59
题目大意: 给定一个字符串,要对这个字符串进行切分,要保证切分后的每个子串为回文串。求最小的切分次数。
解题思路:最小的切分次数,就是切分后回文子串的个数减一。利用动态规划来求解。
dp[i]来表示范围[i, len(str))子串的回文子串的最小个数
i = len(str)时, 初始化 dp[len(str)] = 0
当 i < len(str)时,对于 i< j < len(str);
如果[i, j]范围的子串为回文串,那么dp[i] = min(dp[i], dp[j + 1] + 1);
否则dp[i] = dp[i - 1] + 1.
字符串从右往左扫描时用pal[i][j]表示范围[i, j] 是否为回文串。
如果pal[i + 1][j -1]为true,且str[i] == str[j],则pal[i][j]为true.
#include <iostream>#include <cstdio>#include <string>using namespace std;class Solution {public:int minCut(string s) {int *dp = new int[s.size() + 1];bool **pal = new bool*[s.size()];memset(dp, 0, sizeof(int) * (s.size() + 1));for(int i = 0; i < s.size(); i++) { pal[i] = new bool[s.size()]; memset(pal[i], 0, sizeof(bool) * s.size());}for(int i = s.size() - 1; i >= 0; i--) {dp[i] = dp[i + 1] + 1;for(int j = i + 1; j < s.size(); j++) {if(s[i] == s[j] && (i + 1 < s.size() && (j - i <= 2 || pal[i + 1][j - 1]))) {pal[i][j] = true;dp[i] = min(dp[i], dp[j + 1] + 1);}}}int ans = dp[0];for(int i = 0; i < s.size(); i++) delete[] pal[i];delete[] pal;delete[] dp;return ans - 1;}};
0 0
- 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
- Palindrome Partitioning II
- 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
- LetCode:Palindrome Partitioning II
- LeetCode-Palindrome Partitioning II
- [leetcode] Palindrome Partitioning II
- POSTGRESQL 数据库 函数 操作符 一
- Vitamio Recorder 2.0 源码分析
- 处女男学Android(十)---Fragment完结篇之Fragment通信和ListFragment
- iOS开发笔记--使用Auto Layout中的VFL(Visual format language)--代码实现自动布局
- 零度 大疆调试飞行经验
- Palindrome Partitioning II
- POSTGRESQL 数据库 函数 操作符 二
- 小马哥---高仿华为p7刷机 山寨华为p7 出现市场 真假难辨
- Eclipse HTML Editor
- IKAnalyzer 配置文件介绍
- poj 3280 Cheapest Palindrome (区间dp)
- Android 四大组件 之 Broadcast/Receiver 流程
- C/C++堆栈指引
- UILabel详解