首页 > 其他 > 详细

Leetcode 312. Burst Balloons

时间:2019-01-06 10:08:43      阅读:130      评论:0      收藏:0      [点我收藏+]

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 };

 

Leetcode 312. Burst Balloons

原文:https://www.cnblogs.com/haoweizh/p/10227055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!