LeetCode: 312. Burst Balloons

LeetCode: 312. 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:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100
    Example:
Input: [3,1,5,8]
Output: 167 
Explanation: 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

解题思路 —— 记忆搜索

  1. 记:record[i][j] 为在原气球序列中,区间 [i, j] 的气球炸裂能得到的最大值
  2. 则,record[i][j] = max(record[i][k-1] + record[k+1][j] + nums[i-1]*nums[k]*nums[j+1], ...) 其中 k=i...j (假设区间 [i, j] 中最后爆裂的是下标为 k 的气球)
  3. 由于第 k 个气球最后一个爆裂,因此其左右的气球互相之间都没有了关系(一直都有它在中间隔开)。

AC 代码

func max(lhv, rhv int) int {
    if lhv > rhv {
        return lhv
    } else {
        return rhv
    }
}
func maxCoinsRef(nums []int, record *[][]int, beg int, end int) int{
    if beg > end || beg < 0 || end >= len(nums) {
        return 0
    } else if (*record)[beg][end] !=  -1 {
        return (*record)[beg][end]
    } else if beg == end {
        burstVal := nums[beg]
        if 0 != beg { 
            burstVal *= nums[beg-1]
        }
        if len(nums)-1 != beg {
            burstVal *= nums[beg+1]
        }
        
        (*record)[beg][end] = burstVal
    } else {
        // [beg, end] 的气球 i 最后 burst
        for i := beg; i <= end; i++ {
            burstVal := nums[i]
            if beg != 0 { 
                burstVal *= nums[beg-1]
            }
            if end != len(nums)-1 {
                burstVal *= nums[end+1]
            }
            
            (*record)[beg][end] = max((*record)[beg][end], 
            	maxCoinsRef(nums, record, beg, i-1) + 
            	burstVal +  
            	maxCoinsRef(nums, record, i+1, end))
        }
    }

    return (*record)[beg][end]
}

func maxCoins(nums []int) int {
    if len(nums)== 0 { return 0 }
    
    // record[i][j]: maxCoins(nums[i,j+1])
    record := make([][]int, len(nums))
    for i := 0; i < len(record); i++ {
        record[i] = make([]int, len(nums))
        
        for j := 0; j < len(record[i]); j++ {
            record[i][j] = -1
        }
    }
    
    maxCoinsRef(nums, &record, 0, len(nums)-1)
    
    return record[0][len(nums)-1]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值