Palindrome Partitioning II Leetcode Python

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.

这题的标准解法是用动态规划,我自己先用了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.minval
def 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



你可能感兴趣的:(LeetCode,python,array,dp,BruteForce)