[leetcode]312. Burst Balloons

来源:互联网 发布:淘宝客小猪优惠券 编辑:程序博客网 时间:2024/05/29 18:22

divide and conquer

题目:

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

思路:

在区间[i, j]中,最后的元素的乘积与其两边的值无关,因此可以作为一个边界,其左右两边的结果只与自身的值有关,不与对方的值有关。
所以设left

dp[left][right] = max(dp[left][right], dp[left][m]+dp[m][right]+newnums[left]*newnums[m]*newnums[right]);

代码:

class Solution {public:    int maxCoins(vector<int>& nums) {        vector<int> newnums(nums.size()+2);        int size = nums.size()+2;        newnums[0] = newnums[size-1] = 1;        int i;        for (i = 1; i < size-1; i++) {            newnums[i] = nums[i-1];        }        int dp[size][size] = {};        for (int k = 2; k < size; k++) {            for (int left = 0; left < size-k; left++) {                int right = left+k;                for (int m = left+1; m < right; m++) {                    dp[left][right] = max(dp[left][right], dp[left][m]+dp[m][right]+newnums[left]*newnums[m]*newnums[right]);                    //std::cout << dp[left][right] << endl;;                }            }        }        return dp[0][size-1];    }};
原创粉丝点击