Palindrome Partitioning II Leetcode Python
来源:互联网 发布:nginx 后端监控 编辑:程序博客网 时间:2024/04/27 15:41
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 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.
这题的标准解法是用动态规划,我自己先用了dfs的方法 但是解出来超时。 解法和palindrome I的一样。
class Solution: def check(self,s): for index in range(len(s)): if s[index]!=s[len(s)-index-1]: return False return True def dfs(self,s,count,valuelist): if len(s)==0: #solution.append(valuelist) Solution.minval=min(Solution.minval,count) for index in range(1,len(s)+1): if self.check(s[:index])==True: self.dfs(s[index:],count+1,valuelist+[s[:index]]) def solve(self,s): Solution.minval=10000 self.dfs(s,0,[]) print Solution.minvaldef main(): s="aazbcc" solution=Solution() solution.solve(s)if __name__=="__main__": main()
做法就是当确认最后都分解好的时候计算所用的迭代次数。
另外一种解法是用动态规划的方法 借鉴了 http://www.cnblogs.com/zuoyuan/p/3758783.html
class Solution: # @param s, a string # @return an integer def minCut(self, s): dp=[0 for i in range(len(s)+1)] p=[[False for i in range(len(s))] for j in range(len(s))] for i in range(len(s)+1): dp[i]=len(s)-i for i in reversed(range(len(s)-1)): for j in range(i,len(s)): if s[i]==s[j] and (j-i<2 or p[i+1][j-1]): p[i][j]=True dp[i]=min(dp[i],1+dp[j+1]) return dp[0]-1
0 0
- [Leetcode][python]Palindrome Partitioning/Palindrome Partitioning II
- Palindrome Partitioning II Leetcode Python
- 132. Palindrome Partitioning II Leetcode Python
- 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
- spring开发_Spring+Sturts2
- Linux学习mysql
- bj bku hvh vh
- linux中du和df 的区别
- hdu 5155
- Palindrome Partitioning II Leetcode Python
- Intent数据传递
- 一致性哈希算法与Java实现
- C++模板元编程(C++ template metaprogramming)
- boost源码剖析之:多重回调机制signal(下)
- boost源码剖析之:泛型编程精灵type_traits(rev#2)
- 编写可读代码(二) 如何命名
- 在C++中侦测内嵌型别的存在(rev#2)
- 本文实例分析了js正则表达式中的单行模式与多行模式。分享给大家供大家参考