Burst Balloons

来源:互联网 发布:sql语句里case when 编辑:程序博客网 时间:2024/05/21 11:03

Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on it represented by arraynums. You are asked to burst all the balloons. If the you burst ballooni you will get nums[left] * nums[i] * nums[right] coins. Hereleft and right are adjacent indices of i. After the burst, theleft 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
class Solution {public:    int maxCoins(vector<int>& nums) {        int n = nums.size();        int size = n+2;        int num[size];        for (int i = 0; i < n; i++)        {            num[i+1] = nums[i];        }        num[0] = 1;        num[size-1] = 1;        int buf[size][size];        memset(buf, 0, sizeof(buf));        for (int i = 2; i < size; i++)        {            for (int left = 0; left+i < size; left++)            {                int right = left+i;                for (int j = left+1; j < right; j++)                {                     //该等式意味着在left和i之间,以及i与right之间的气球都已经被用完.                     //所以这时获得的值是num[left]*num[j]*num[right].                     //同时,由于在left和i之间的气球用完时,会用到num[j]的值,因此要加上buf[left][j].                     //同理,也要加上buf[j][right].                    buf[left][right] = max(buf[left][right],                                         buf[left][j] + num[left]*num[j]*num[right] + buf[j][right]);                }            }        }        return buf[0][size-1];    }};


0 0
原创粉丝点击