zoukankan      html  css  js  c++  java
  • LN : leetcode 312 Burst Balloons

    lc 312 Burst Balloons


    312 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 Accepted

    这道题目应该从逆向来思考,选择以某个气球为分割点,那么其左边部分和右边部分都要依赖与那个气球。dp[i][j]表示到最后只剩下i和j所产生金币的最大值,对于i和j之间的k,如果引爆k,那么dp[i][j]被更新成max(dp[i][j], nums[i]*nums[k]*nums[j]+dp[i][k]+dp[k][j]),所以想要得到这个数组最大金币值,需要在首尾各加上一个元素,值为1,此时答案即为dp[0][len-1]。

    class Solution {
    public:
        int maxCoins(vector<int>& nums) {
            if (nums.size() == 0)   return 0;
            nums.insert(nums.begin(), 1);
            nums.insert(nums.end(), 1);
            int len = nums.size();
            vector<vector<int>> dp(len, vector<int>(len, 0));
            for (int i = len-3; i >= 0; i--) {
                for (int j = i+2; j < len; j++) {
                    for (int k = i+1; k < j; k++) {
                        dp[i][j] = max(dp[i][j], nums[i]*nums[k]*nums[j]+dp[i][k]+dp[k][j]);
                    }
                }
            }
            return dp[0][len-1];
        }
    };
    
  • 相关阅读:
    HDU 4644 BWT (KMP)
    常数的值类型问题
    HDU 1395 2^x mod n = 1 (欧拉函数)
    HDU 5384 Danganronpa(AC自动机)
    9.自己实现linux中的tree
    8.底层文件库
    7.标准文件库
    7.gcc的使用
    5.文件I/O
    4.vim操作
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7869102.html
Copyright © 2011-2022 走看看