[LeetCode]Burst Balloons

来源:互联网 发布:formal mac 编辑:程序博客网 时间:2024/06/05 10:01

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. Hereleft 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

动态规划  和数据结构预算法分析中的经典例题,求矩阵链乘最大乘法次数是一样的

public class Solution {    public int maxCoins(int[] input) {    if(input.length==0) return 0;    int[] nums=new int[input.length+2];    nums[0]=nums[nums.length-1]=1;    for(int i=0;i<input.length;i++) nums[i+1]=input[i];    int[][] dp=new int[nums.length][nums.length];    for(int len=1;len<nums.length;len++){    for(int i=0;i<nums.length-len;i++){    int j=i+len;    dp[i][j]=0;    for(int l=i+1;l<j;l++){    dp[i][j]=Math.max(dp[i][j], dp[i][l]+dp[l][j]+nums[i]*nums[l]*nums[j]);    }    }    }    return dp[0][nums.length-1];    }}