[leetcode] 312. Burst Balloons 解题报告

46 篇文章 1 订阅
3 篇文章 0 订阅

题目链接:https://leetcode.com/problems/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

思路:考虑分治法来处理的时候,如果选择以某个气球为分割点,那么其左边部分和右边部分都要依赖与那个气球,因此我们不能让这个气球先爆.也就是说我们选择分割点的时候不是选择先爆的气球,而是最后爆的气球,这样分成的左右两个部分将相互独立.即如果最后只剩下气球i,那么其最后只依赖与第0和n-1个气球,而在[0, i] 和 [i, n-1]两个区间是相互独立的,这样我们就可以将问题分割为相互独立的子集.这样时间复杂为O(n^n). 但是在枚举各个分割点的时候会有很多重复的计算,因此我们可以保存已经计算过的区间.这样时间复杂度可以优化到O(n^3).


同样我们也可以使用动态规划来处理,其原理和分治一样,也是分区间由小到大最后完成整个计算.

两种代码如下:

class Solution {
public:
    int divid(vector<int>& nums, vector<vector<int>>& dp, int low, int high)
    {
        if(low+1 == high) return 0;
        if(dp[low][high] > 0) return dp[low][high];
        int ans = 0;
        for(int i = low+1; i < high; i++)
            ans=max(ans, nums[low]*nums[i]*nums[high]
                + divid(nums, dp, low, i) + divid(nums, dp, i, high));
        dp[low][high] = ans;
        return ans;
    }
    
    int maxCoins(vector<int>& nums) {
        nums.insert(nums.begin(), 1);
        nums.insert(nums.end(), 1);
        vector<vector<int>> dp(nums.size()+1, vector<int>(nums.size()+1, 0));
        return divid(nums, dp, 0, nums.size()-1);
    }
};

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        if(nums.size()==0) return 0;
        nums.insert(nums.begin(), 1);
        nums.insert(nums.end(), 1);
        int len = nums.size();
        vector<vector<int>> dp(len, vector<int>(len, 0));
        for(int i = len-3; i >= 0; i--)
        {
            for(int j = i+2; j < len; j++)
            {
                for(int k = i+1; k < j; k++)
                    dp[i][j]=max(dp[i][j], nums[i]*nums[j]*nums[k]+dp[i][k]+dp[k][j]);
            }
        }
        return dp[0][len-1];
    }
};












  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值