LeetCode #312: Burst Balloons

129 篇文章 0 订阅
14 篇文章 0 订阅

Problem Statement

(Source) 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

Analysis

This problem has an obvious indication that we can use Dynamic Programming approach to solve it. After making a decision on using dynamic programming, the next step is to find the recurrence structure of how global optimal solution can be formed by optimal solutions of sub-problems.

Let dp[i][j] denotes the optimal solution for the array slice nums[i : j + 1]. Put it in another way, dp[i][j] means the number of coins we can get when we only burst balloons indexed from i to j. At this point, we get stuck, so let us try from small input size. What if the input array is of size 1? The solution would be the number on this single balloon. Then think about what if the input array if of size 2? In this case, what matters is the last balloon we burst, right? Because the coins we get by our first bursting would be the same no matter which ballon we choose to burst first, and we have to burst twice. Now, we may formulate our Dynamic Programming Recurrence:

# k is the last balloon we choose to burst in range i...j.
for k in i...j:     
    dp[i][j] = max(dp[i][j], nums[i - 1] * nums[k] * nums[j + 1] + dp[i][k - 1] + dp[k + 1][j])

Solution

class Solution(object):
    def maxCoins(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0

        n = len(nums)
        nums.insert(0, 1)
        nums.append(1)
        dp = [[0 for i in xrange(n + 2)] for j in xrange(n + 2)]
        dp[0][0] = 1
        dp[n + 1][n + 1] = 1
        for length in xrange(1, n + 1):
            for i in xrange(1, n - length + 2):
                j = i + length - 1
                for k in xrange(i, j + 1):
                    dp[i][j] = max(dp[i][j], nums[i - 1] * nums[k] * nums[j + 1] + dp[i][k - 1] + dp[k + 1][j])

        return dp[1][n]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值