[leetcode]Palindrome Partitioning II @ Python


原題地址:https://oj.leetcode.com/problems/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.

解題思路:由於這次不需要窮舉出所有符合條件的回文分割,而是需要找到一個字符串s回文分割的最少分割次數,分割出來的字符串都是回文字符串。求次數的問題,不需要dfs,用了也會超時,之前的文章說過,求次數要考慮動態規划(dp)。對於程序的說明:p[i][j]表示從字符i到j是否為一個回文字符串。dp[i]表示從第i個字符到最后一個字符,最少的分割次數下,有多少個回文字符串,即分割次數+1。這道題動態規划的思路比較簡單,直接上代碼吧。

代碼:

class Solution:
    # @param s, a string
    # @return an integer
    # @dfs time out
    # @dp is how many palindromes in the word
    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 range(len(s)-1, -1, -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(1+dp[j+1], dp[i])
        return dp[0]-1

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM