leetcode 312 : Burst Balloons

来源:互联网 发布:淘宝售后培训ppt 编辑:程序博客网 时间:2024/05/17 08:48

1、原题如下:

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

2、解题如下:

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