【Leetcode】312. Burst Balloons

Description:

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

思路:

首先,如果直接来解这道题的话,循环计算所有气球中三个相邻的气球分数最大积,要计算n!次,这样时间复杂度会达到O(n!),当随着气球总数增加,效率会急剧下降,因此需要进行一些优化。
每次求数组最大积时其实有很多重复的操作,比如在计算一次击破气球的得分时,在下一轮计算中,原本不相邻变得相邻的气球的得分积会再次被用到,而此时如果利用空间来存储这些积,可以提高效率。另外,当两个气球变得相邻之后,最大的积可从这两个数的左右侧得到,那么据此我们可以进行分治,即从某个气球开始,计算其打破时的得分和对其左右两边进行递归。以下是使用C++的实现过程。

class Solution{
    public:
    int maxCoins(vector<int>& nums) {
        int arr[nums.size()+2];
        int n = nums.size()+1;
        for (int i=0; i<nums.size(); i++) if (arr[i] > 0) arr[i+1] = nums[i];
        arr[0] = arr[n] = 1;//使得原本不存在的nums[-1]和nums[n]得以计算

        int temp[n][n];//建立一个n×n的数组来作为中间变量存储做过的乘积操作
        return burst(temp, arr, 0, n-1);
    }

    int burst(int temp, int arr, int left, int right) {
        if (left + 1 == right) return 0;
        if (temp[left][right] > 0) return temp[left][right];
        int max_coins = 0;
        for (int i=left+1; i<right; i++)
            max_coins = max(max_coins, arr[left]*arr[i]*arr[right] + burst(temp, arr, left, i) + burst(temp, arr, i, right));
        temp[left][right] = max_coins;
        return max_coins;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值