zoukankan      html  css  js  c++  java
  • Leetcode 312. 戳气球

    题目

    n 个气球,编号为0n-1,每个气球上都标有一个数字,这些数字存在数组 nums 中。

    现在要求你戳破所有的气球。每当你戳破一个气球 i 时,你可以获得 nums[left] * nums[i] * nums[right] 个硬币。 这里的 left 和 right 代表和 i 相邻的两个气球的序号。注意当你戳破了气球 i 后,气球 left 和气球 right 就变成了相邻的气球。

    求所能获得硬币的最大数量。

    说明:

    • 你可以假设 nums[-1] = nums[n] = 1,但注意它们不是真实存在的所以并不能被戳破。
    • 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100

    示例:

    输入: [3,1,5,8]
    输出: 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
    
    
    public int maxCoins(int[] nums) {
        //DP: the result depends on the last burst balloon, which seprate the array into 2 subarray. 
        //DP: by adding 1 to head and tail, DP[i,i] = 0 and DP[i,i+2] = num[i] * num[i+1] * num[i+2]
        int n = nums.length+2;
        int[] newnums = new int[n];
        for (int i = 0;i < n - 2; i++){
            newnums[i+1] = nums[i];
        }
        newnums[0] = newnums[n - 1] = 1;
        int[][] DP = new int[n][n];
        for (int k = 2; k < n; k++){
            for (int l = 0; l + k < n; l++){
                int h = l + k;
                for (int m = l + 1; m < h; m++){
                    DP[l][h] = Math.max(DP[l][h],newnums[l] * newnums[m] * newnums[h] + DP[l][m] + DP[m][h]);
                }
            }
        }
        return DP[0][n - 1];
    }
    
    
  • 相关阅读:
    Dos命令大全(收藏)
    asp.net读写Cookies
    asp.net文件下载
    使用存储过程分页
    (十)死锁检测算法
    poj1664
    一席话惊醒梦中人
    深入了解scanf()/getchar()和gets()/cin等函数
    小结《malloc与new之区别》
    (六)文件管理
  • 原文地址:https://www.cnblogs.com/qq874455953/p/10264434.html
Copyright © 2011-2022 走看看