码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ:Burst Balloons(击破气球)

时间:2015-12-27 22:02:01      阅读:713      评论:0      收藏:0      [点我收藏+]

标签:

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

dp问题,开始没想出来唉,看了下别人的。就是从left和right间的间距从2开始,一直递推到相差n-1这种情况。代码如下所示:

 1 class Solution {
 2 public:
 3     static bool noCoins(int a)
 4     {
 5         return a == 0;
 6     }
 7     int maxCoins(vector<int>& nums) {
 8         nums.erase(remove_if(nums.begin(), nums.end(), noCoins), nums.end());//注意这里的处理方法。先调用remove在调用erase
 9         if(nums.size() == 0) 
10             return 0;
11         nums.resize(nums.size() + 2);
12         copy(nums.begin(), nums.end() - 2, nums.begin() + 1);
13         nums[0] = nums[nums.size() - 1] = 1;
14         int sz = nums.size();
15         int dp[sz][sz] = {};
16         for(int interval = 2; interval < sz; ++interval){//interval指的是left与right之间的间隔
17             for(int left = 0; left < sz - interval; ++left){
18                 int right = left + interval;
19                 for(int j = left + 1; j < right; ++j){//穷尽left-right之间的每一种可能值
20                     dp[left][right] = max(dp[left][right], dp[left][j] + nums[left]*nums[j]*nums[right] + dp[j][right]);
21                  }                                                       //注意这里取left以及right的原因是left到j之间的数字以及被dp[left][j]所覆盖了
22             }
23         }
24         return dp[0][sz-1];//这是最终结果了
25     }
26 };

 

LeetCode OJ:Burst Balloons(击破气球)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/5013089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!