leetcode.312. Burst Balloons

来源:互联网 发布:软件咨询服务合同模板 编辑:程序博客网 时间:2024/05/03 16:14
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 getnums[left] * nums[i] * nums[right] coins. Hereleft and right are adjacent indices ofi. After the burst, theleft andright 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

思路

考虑最后一个戳破的气球,这个气球的位置可以把整个气球数组分成两部分。 
 
利用动态规划思路:

动态规划数组:
    DP[k][h]:nums[k...h]能戳破气球的最大值
递推关系:
    取k<m<h,nums[m]假设是最后一个戳破的气球
    则DP[k][h] =
    for (m = k+1...h)
        max(DP[k][m] + DP[m][h] + nums[k] * nums[m] * nums[h]);
初始值:
    需要扩展nums,数组长+2,头和尾分别加入1
    DP[k][h]:
        当k + 1 = h 或 k = h时,为0;
        当k + 2 = h 时,为 nums[k] * nums[k+1] * nums[k+2];

class Solution {public:    int maxCoins(vector<int>& nums) {        int n = nums.size()+2;        vector<int> newnums(n);        for (int i = 0;i < n - 2; i++){           newnums[i+1] = nums[i];        }        newnums[0] = newnums[n - 1] = 1;        vector<int> tmp(n,0);        vector<vector<int>> DP(n,tmp);        for (int k = 2; k < n; k++){            for (int l = 0; l + k < n; l++){               int h = l + k;               for (int m = l + 1; m < h; m++){                   DP[l][h] = max(DP[l][h],newnums[l] * newnums[m] * newnums[h] + DP[l][m] + DP[m][h]);               }            }        }        return DP[0][n - 1];    }};



                                             
0 0
原创粉丝点击