分治与动态规划之Burst Balloons问题

来源:互联网 发布:苹果电脑怎么更新软件 编辑:程序博客网 时间:2024/06/10 21:04

Burst Balloons

A.题意

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

题目的大概意思是,给你n个气球,戳破某个气球得到该气球和它左右两个气球上数字的乘积,然后去掉改气球,使得其左右两边的气球变成相邻,问最后所有乘积相加最大值是什么。

题目中给了个例子:
Given [3, 1, 5, 8]
Return 167
它是这样一个过程
[3,1,5,8] –> [3,5,8] –> [3,8] –> [8] –> []
对应的coins则为3*1*5+3*5*8+1*3*8+1*8*1=167

B.思路

我是在leetcode的分治那部分看到这道题的,一开始毫无思路,因为假如要分治,你把(i,j)中的k戳破,然后把该序列分成(i,k-1],[k+1,j)的话两个序列是彼此影响的,因为这时候k-1和k+1变成相邻的了,然后翻看讨论区看到了其实这道题应该换种思路,把k当成是i到j中最后一个戳破的气球,这样子问题之间就没有联系了,就可以分治了,我们结合动态规划用表格来记录i到j的最大结果,就可以得到该迭代式

table[i][j] = max(table[i][j],myNums[i] * myNums[k] * myNums[j] + table[i][k] + table[k][j]);

C.代码实现

class Solution {public:    int maxCoins(vector<int>& nums) {        int size = nums.size();        int myNums[size + 2];        for (int i = 1;i < size + 1;i++)        {            myNums[i] = nums[i - 1];        }        myNums[0] = 1;        myNums[size + 1] = 1;        int table[size + 2][size + 2] = {};        for (int i = 0;i < size + 2;i++)        {            table[i][i] = myNums[i];        }        for (int len = 2;len < size + 2;len++)        {            for (int i = 0;i < size + 2 - len;i++)            {                int j = i + len;                for (int k = i + 1;k < j;k++)                {                    table[i][j] = max(table[i][j],myNums[i] * myNums[k] * myNums[j] + table[i][k] + table[k][j]);                }            }        }        return table[0][size + 1];    }};
原创粉丝点击