zoukankan      html  css  js  c++  java
  • [leetcode] 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问题,关键是要如何转化为最优子结构问题求解,我们以最后被爆破的气球为界限,把数组分为左右两个子区域,然后分别在每个子区域中递归求解,可以用一个数组dp[i][j]记忆从下标i到下标j之间的最大coins,防止重复计算。

    Java代码:

        public int maxCoins(int[] nums) {
            if(nums == null) return 0;
            int[] array = new int[nums.length+2];
            int i = 1;
            for(int num:nums) {
                if(num != 0)
                    array[i++] = num;
            }
            array[0] = 1; array[i] = 1;
            int[][] dp = new int[nums.length+2][nums.length+2];
            return helper(array, dp, 0, i);
        }
        
        public int helper(int[] array, int[][] dp, int i, int j) {
            if(i+1 >= j) return 0;
            if(dp[i][j] > 0) return dp[i][j];
            int res = 0;
            for(int k = i+1; k < j; k++) {
                res = Math.max(res, array[i]*array[k]*array[j] + helper(array, dp, i, k) + helper(array, dp, k, j));
            }
            dp[i][j] = res;
            return res;
        }
  • 相关阅读:
    Burp Suite抓包使用步骤
    抓包工具Burp Suite安装步骤(待补充)
    mysql版本和模式查询
    git仓库下拉和上传
    git仓库个人和企业版新增仓库和成员
    漏洞扫描工具acunetix破解安装步骤
    漏洞扫描工具acunetix12会遇到的问题
    memcached缓存:安装和清缓存
    oracle数据库备份、还原命令及常见问题(待补充)
    Linux中,关闭selinux
  • 原文地址:https://www.cnblogs.com/lasclocker/p/5009298.html
Copyright © 2011-2022 走看看