8.24 - hard - 101

546. Remove Boxes

先做出來一個backtracking的TLE版本,下面想想如何加memory, memory其實也是DP,狀態(tài)和轉(zhuǎn)移方程如下:
memo[l][r][3] 表示這樣狀態(tài)的解: [b_l, ..., b_r, A,A,A] with b_r==A
memo[l][r][k] = max(memo[l][r][k], memo[l][i][k+1] + memo[i+1][r-1][0])

Basically, if there is one i such that b_i==b_r, we partition the array into two: [b_l, ..., b_i, b_r, A, ..., A], and [b_{i+1}, ..., b_{r-1}]. The solution for first one will be memo[l][i][k+1], and the second will be memo[i+1][r-1][0]. Otherwise, we just remove the last k+1 boxes (including b_r) and search the best solution for lth to r-1th boxes

class Solution(object):
    def removeBoxes(self, boxes):
        """
        :type boxes: List[int]
        :rtype: int
        """
        if not boxes:
            return 0
        n = len(boxes)
        dp = [[[0]*n for _ in range(n)] for _ in range(n)]
        return self.search(dp, boxes, 0, n-1, 0)
    
    def search(self, dp, boxes, i, j, k):
        if i > j:
            return 0
        if dp[i][j][k] > 0:
            return dp[i][j][k]
        while j > i and boxes[j]==boxes[j-1]:
            j -= 1
            k += 1
        dp[i][j][k] = self.search(dp, boxes, i, j-1, 0) + (k+1)**2
        for m in range(i, j):
            if boxes[j] == boxes[m]:
                dp[i][j][k] = max(dp[i][j][k], self.search(dp, boxes, i, m, k+1) + self.search(dp, boxes, m+1, j-1, 0))
        return dp[i][j][k]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容