Leetcode 312. Burst Balloons

Problem:

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:

  • You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them.
  • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

Example:

Input: [3,1,5,8]
Output: 167 
Explanation: 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
Solution:

  这道题是分治和动态规划的结合,难度还是很大的,我们需要维护一个二维数组,dp[i][j]表示删除第i个数和第j个数得到的最大分数,因此,要得到dp[i][j],我们只需要遍历i到j,假设t为最后一个删除的元素,dp[i][j]就等于dp[i][t-1]+dp[t+1][j]+nums[i-1]*nums[i]*nums[j+1]。找到一个t使得得分最大即可。

Code:

 

 1 class Solution {
 2 public:
 3     int maxCoins(vector<int>& nums) {
 4         int m = nums.size();
 5         nums.insert(nums.begin(),1);
 6         nums.push_back(1);
 7         vector<vector<int>> dp(m+2,vector<int>(m+2,0));
 8         for(int len = 1;len <= m;++len){
 9             for(int left = 1;left <= m-len+1;++left){
10                 int right = left + len - 1;
11                 for(int i = left;i <= right;++i){
12                     dp[left][right] = max(dp[left][right],nums[left-1]*nums[i]*nums[right+1]+dp[left][i-1]+dp[i+1][right]);
13                 }
14             }
15         }
16         return dp[1][m];
17     }
18 };

 

posted on 2019-01-06 05:38  周浩炜  阅读(168)  评论(0编辑  收藏  举报

导航