5

leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)

 3 years ago
source link: https://blog.csdn.net/ljphhj/article/details/22573983
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

leetCode解题报告之Palindrome Partitioning I,II(DFS,DP)

题目:

Palindrome Partitioning

 I

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

分析:

题意给我们一个字符串,求出所有这个字符串的子串,并且子串都为回文字符串的情况,输出它的集合结果

解题思路:(跟DFS深度遍历有点像!)

字符串Str = "aab";

分析了题目的数据之后,我们知道它的结果,可能是 a, a, b 或者  aa, b 这样的情况!

也就是说,我们需要去考虑 i = 1,  2 ....  n 的情况,比如

Str = "aaa"

[[a, a, a], [a, aa], [aa, a], [aaa]]

根据这样的情况,我们用类似于DFS的算法

str1 = str.substr(0, i); 取出前面下标从 0 开始到 i 结束的子串,判断str1是否满足回文字符串的要求,

1. 满足:这样子,有可能成为一种分割的情况,所以我们new出一个list集合,把str1放入到list中,然后我们求出str剩余的子串  str2 = str.substr(i); 取出前面下标从 i 开始到整个字符串结尾的子串, 然后将str2 作为新的字符串,同时把list集合也传入到函数中,递归调用。递归的结束条件就是到传入的这个字符串的长度为0(这样就意味着已经到了字符串的末尾了),此时证明这种情况下得到的list集合是满足条件的,我们把这个list集合 加入到 结果集合result中。

2. 不满足的话,继续 i++, 直到 i == str.length();

3. 全部结束之后,返回 最终的结果集合 result

AC代码:

题目:(DP)

Palindrome Partitioning II

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做的,但上一题我们没有用那种方法,但是这题要用DP哈,不然会TLE哦)

解题思路:

我们可以把这个问题转换成动态规划dp的问题

首先我们先定义几个变量,并对这几个量做一定的说明!为了方便理解,下面这些为伪码!!!

len  = str.length();   // 字符串的长度

int[] cuts = new int[len + 1]; //cuts数组,cuts[i] 表示 以 i 开头到len结尾的子串 要达到题意需要的最少切割数(这样子最终 cuts[0]就是我们要的结果)【初始化 cuts[i] = len - i, 因为最坏情况以 i 开头到len结尾的子串要切割数就是每个字符都切一次】

int[][] matrix = new  int[len][len]; //设置出一个邻接矩阵数组,它所表示的意思:如matrix[i][j] = true, 表示 子串 sub(i, j) 是满足回文字符串条件的!

那么判断matrix[i][j] 是否满足回文字符串的条件是: 

matrix[i+1][j-1] == true (表示sub(i+1,j-1)是满足回文字符串) && str[i] == str[j] 

j - i < 2 && str[i] == str[j] (即如果j - i == 1时,为两个字符相等,如果j - i == 0时,为同一个字符) 

这两种情况,我们都将matrix[i][j]设置成true,方便下一次的DP,并且我们可以求出最小的切割次数

cuts[i] = min{cuts[i], cuts[j+1] + 1};  状态转移方程式

这样最后cuts[0] - 1便为 字符串str的最小的切割数!!!!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK