zoukankan      html  css  js  c++  java
  • LeetCode OJ:Burst Balloons(击破气球)

    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 };
  • 相关阅读:
    webService 服务端搭建
    ss2h 整合
    Java绘制登陆验证码
    c3p0连接池
    DBCP连接池
    Cglib动态代理
    会话技术(Cookie,Session)
    Tomcat设置角色和密码
    转发和重定向
    JDK动态代理
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5013089.html
Copyright © 2011-2022 走看看