Hard-题目3:312. Burst Balloons

本文介绍了一个气球爆破游戏的问题,并通过动态规划的方法解决了该问题。玩家需要爆破所有气球以获得最大收益,收益由爆破气球与其相邻两个气球上的数字的乘积决定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目原文:
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个气球,每个气球上有一个数字,进行以下的游戏:玩家每次刺破一个气球,获得m元钱,其中m为刺破的气球及其相邻两个气球上面的数字的乘积(规定第-1个和第n个气球上的数字为1,相当于边缘的气球只考虑一边即可),计算玩家可能获得的最大收益。
题目分析:
设dp[i][j]表示从第i个气球到第j个气球的最大收益,则有如下转移方程:

dp[i][j]=min⁡(dp[i][k-1]+num[k-1]*num[k]*num[k+1]+dp[k+1][j]),k∈(i,j)

很好理解,从第i个气球到第j的气球的最大收益要暴力枚举从其中的第k位刺破所带来的收益。最终问题即求dp[1][n].
源码:(language:cpp)

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        for(int i=0;i<nums.size();++i){
            if(nums[i]==0){
                nums.erase(nums.begin()+i);
                --i;
            }
        }
        int n=nums.size();
        if(n==0) return 0;
        nums.insert(nums.begin(),1);
        nums.insert(nums.end(),1);
        int m=nums.size();
        vector<vector<int>> dp(m,vector<int>(m,0));
        for(int count=1;count<=n;++count){
            for(int start=1;start+count-1<=n;++start){
                int bestcoins=0;
                for(int b=0;b<count;++b){
                    bestcoins=max(bestcoins,dp[start][start+b-1]+nums[start-1]*nums[start+b]*nums[start+count]+dp[start+b+1][start+count-1]);

                }
                dp[start][start+count-1]=bestcoins;
            }

        }
        return dp[1][n];
    }
};

成绩:
36ms,beats 61.75%,众数44ms,22.51%
Cmershen的碎碎念:
本题的转移方程及其实现都不难,难在想到这个递推关系。而通常会想到回溯法,显然要暴力枚举每种扎气球的方法,其复杂度为O(n!),在n=500的数据量下是不能接受的。考虑到每扎破一个气球,都退化成求两边的最佳扎破方法,故可以使用dp,本算法复杂度O(n3).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值