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];
        }
    };
    
  • 相关阅读:
    SQL Server 查看存储过程执行次数的方法
    css背景图片拉伸 以及100% 满屏显示
    时间倒计时
    对于解决 缓存问题
    HTML5 隐藏地址栏 兼容IOS 与安卓
    多行文字实现垂直居中 css3
    div中溢出文字用点代替
    左侧固定 右侧自适应 布局
    两个DIV第一个用了定位后 如何让两个DIV 落在一起
    String.Format,DateTime日期时间格式化
  • 原文地址:https://www.cnblogs.com/renleimlj/p/7869102.html
Copyright © 2011-2022 走看看