• [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;
        }
  • 相关阅读:
    使用反射调用某个类的成员方法
    java反射机制
    SVProgressHUD
    __objc__
    loadView
    v2ex 下拉刷新 SCRootViewController
    stuck with
    v2ex 下拉刷新模块
    转载
    vue-cli脚手架构建了项目如何去除Eslint验证(语法格式验证)
  • 原文地址:https://www.cnblogs.com/lasclocker/p/5009298.html
Copyright © 2020-2023  润新知