LeetCode 312. Burst Balloons(Hard)

Burst Balloons(Hard)

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

Analysis
这道题真的好难啊!错了无数遍。= =
题目的意思其实就是通过设定踩爆的气球的顺序来获得最多的硬币数。由于这个题目的分组是在分治算法上,所以这个题肯定是要用分治算法的。
但后来发现这道题需要采用动态规划的思想。通过设立一个二维数组result[i][j]来表示踩爆两个气球之间的可以获得的最大硬币数。最后返回result[0][n-1]来表示结果。注意一个点是可以利用最后一个被踩爆的气球来将问题分为两个独立的子问题来计算。

Code

class Solution {
public:
    int maxCoins(vector<int>& nums) {
        int n = nums.size() + 2;
        int result[n][n] ;

        for(int i = 0 ; i < n;++i){
            for(int j = 0 ;j <n;++j){
                result[i][j] = 0;
            }
        }

        int arr[n] ;
        arr[0] = 1 ;
        arr[n-1] = 1 ;
        for(int i = 1 ; i<n-1 ; ++ i){
            arr[i] = nums[i - 1] ;
        }

        for(int k = 2 ; k < n; ++ k){
            for(int i = 0 ; i < n - k ; ++ i ){
                int j = i + k;
                for(int l = i + 1 ; l < j ; ++ l){
                    result[i][j] = max(result[i][j] , arr[i]*arr[l]*arr[j] + result[i][l]+result[l][j]);
                }
            }
        }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值