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 getnums[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.
nums[-1] = nums[n] = 1
. They are not real therefore you can not burst them.- 0 ≤ n
≤ 500, 0 ≤ nums[i]
≤ 100 Example
Given [4, 1, 5, 10]
270
nums = [4, 1, 5, 10] burst 1, get coins 4 * 1 * 5 = 20nums = [4, 5, 10] burst 5, get coins 4 * 5 * 10 = 200 nums = [4, 10] burst 4, get coins 1 * 4 * 10 = 40nums = [10] burst 10, get coins 1 * 10 * 1 = 10Total coins 20 + 200 + 40 + 10 = 270 递归做法:
1 public class Solution { 2 public int maxCoins(int[] nums) { 3 if (nums == null || nums.length == 0) return 0; 4 Listlist = new LinkedList<>(); 5 for (int index = 0; index < nums.length; index++) { 6 list.add(nums[index]); 7 } 8 return helper(list); 9 }10 11 public int helper(List list) {12 if (list.size() == 1) return list.get(0);13 int max = 0;14 for (int i = 0; i < list.size(); i++) {15 int value = getValue(list, i) * getValue(list, i - 1) * getValue(list, i + 1);16 List temp = new LinkedList<>(list);17 temp.remove(i);18 max = Math.max(max, value + helper(temp));19 }20 return max;21 }22 23 private int getValue(List list, int index) {24 if (index < 0 || index >= list.size()) {25 return 1;26 } 27 return list.get(index);28 }29 }
方法二:
既然递归通不过,只能用DP,关键是那个递归式怎么写啊?
在从1到n个气球里,哪个会是最后一个呢?你不知道吧?我也不知道。所以我们得从头到尾假设第k个球是最后一个球。如果第k个球是最后一个球,会有什么性质呢?我们可以保证一定第k个球左边和右边的球永远不会靠在一起,换句话说,我们可以得到下面的递推式:
dp[i][j] = max(dp[i][j], nums[i - 1]*nums[k]*nums[j + 1] + dp[i][k - 1] + dp[k + 1][j]) ( i ≤ k ≤ j )
1 public class Solution { 2 public int maxCoins(int[] nums) { 3 if (nums == null || nums.length == 0) return 0; 4 5 Listlist = new ArrayList<>(); 6 list.add(1); 7 for (int index = 0; index < nums.length; index++) { 8 list.add(nums[index]); 9 }10 list.add(1);11 12 int[][] dp = new int[list.size()][list.size()];13 int n = nums.length;14 for (int step = 0; step <= n - 1; step++) {15 for (int i = 1; i <= n - step; i++) {16 int j = i + step;17 for (int k = i; k <= j; k++) {18 dp[i][j] = Math.max(dp[i][j],19 list.get(i - 1) * list.get(k) * list.get(j + 1) + dp[i][k - 1] + dp[k + 1][j]);20 }21 }22 }23 return dp[1][n];24 }25 }