10 Burst Balloons

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by array nums. You are asked to burst all the balloons. If the you burst balloon i you will get nums[left] nums[i] nums[right] coins. Here left and right are adjacent indices of i. After the burst, the left and right then becomes adjacent.

Find the maximum coins you can collect by bursting the balloons wisely.

Note: (1) You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Given [3, 1, 5, 8]

Return 167

 nums = [3,1,5,8] --> [3,5,8] -->   [3,8]   -->  [8]  --> []
   coins =  3*1*5      +  3*5*8    +  1*3*8      + 1*8*1   = 167

https://leetcode.com/problems/burst-balloons/

思路:Top down 递推公式是 dp[l,r] = max(dp[l,i]+ dp[i+1,r] + nums[i]*nums[l]*nums[r]) for i in [l+1, r-1]。 因为是top down嘛。所以要用个memo来存一下。

class Solution(object):
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        self.memo = {}
        nums = [1] + nums + [1]
        res = self.dfs(nums, 0, len(nums)-1)
        return res

    def dfs(self, nums, l, r):

        if (l,r)  not in self.memo:
            if l+1 == r: return 0

            res = 0
            for i in range(l+1, r):
                tmp = self.dfs(nums, l, i) + self.dfs(nums, i, r) + nums[i]*nums[l]*nums[r]
                res = max(res, tmp)
            self.memo[(l, r)] = res

        return self.memo[(l, r)]

results matching ""

    No results matching ""