|
| 1 | +package leetcode; |
| 2 | + |
| 3 | +/** |
| 4 | + * Project Name : Leetcode |
| 5 | + * Package Name : leetcode |
| 6 | + * File Name : BurstBalloons |
| 7 | + * Creator : Edward |
| 8 | + * Date : Jan, 2018 |
| 9 | + * Description : 312. Burst Balloons |
| 10 | + */ |
| 11 | +public class BurstBalloons { |
| 12 | + /** |
| 13 | + * Given n balloons, indexed from 0 to n-1. Each balloon is painted with a number on |
| 14 | + * it represented by array nums. You are asked to burst all the balloons. |
| 15 | + * If the you burst balloon i you will get nums[left] * nums[i] * nums[right] coins. |
| 16 | + * Here left and right are adjacent indices of i. After the burst, |
| 17 | + * the left and right then becomes adjacent. |
| 18 | +
|
| 19 | + Find the maximum coins you can collect by bursting the balloons wisely. |
| 20 | +
|
| 21 | + Note: |
| 22 | + (1) You may imagine nums[-1] =å nums[n] = 1. They are not real therefore you can not burst them. |
| 23 | + (2) 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 |
| 24 | +
|
| 25 | + Example: |
| 26 | +
|
| 27 | + Given [3, 1, 5, 8] |
| 28 | +
|
| 29 | + Return 167 |
| 30 | +
|
| 31 | + nums = [3,1,5,8] --> [3,5,8] --> [3,8] --> [8] --> [] |
| 32 | + coins = 3*1*5 + 3*5*8 + 1*3*8 + 1*8*1 = 167 |
| 33 | + i j |
| 34 | + 1 3 1 5 8 1 |
| 35 | + 3 1 8 |
| 36 | + 1 5 1 |
| 37 | +
|
| 38 | + dp[i][j]为打破的气球为i~j之间 |
| 39 | + dp[i][j] = max(dp[i][j], dp[i][x – 1] + nums[i – 1] * nums[x] * nums[j + 1] + dp[x + 1][j]); |
| 40 | +
|
| 41 | + 1 for |
| 42 | + 2 dfs + memo |
| 43 | +
|
| 44 | + time : O(n^3) |
| 45 | + space : O(n^2) |
| 46 | +
|
| 47 | + [3, 1, 5, 8] |
| 48 | + 1 3 1 5 8 |
| 49 | +
|
| 50 | + * @param nums |
| 51 | + * @return |
| 52 | + */ |
| 53 | + |
| 54 | + public int maxCoins(int[] nums) { |
| 55 | + int n = nums.length; |
| 56 | + int[] arr = new int[n + 2]; |
| 57 | + for (int i = 0; i < n; i++) { |
| 58 | + arr[i + 1] = nums[i]; |
| 59 | + } |
| 60 | + arr[0] = arr[n + 1] = 1; |
| 61 | + int[][] dp = new int[n + 2][n + 2]; |
| 62 | + return helper(1, n, arr, dp); |
| 63 | + } |
| 64 | + |
| 65 | + private int helper(int i, int j, int[] nums, int[][] dp) { |
| 66 | + if (i > j) return 0; |
| 67 | + if (dp[i][j] > 0) return dp[i][j]; |
| 68 | + for (int x = i; x <= j; x++) { |
| 69 | + dp[i][j] = Math.max(dp[i][j], helper(i, x - 1, nums, dp) |
| 70 | + + nums[i - 1] * nums[x] * nums[j + 1] |
| 71 | + + helper(x + 1, j, nums, dp)); |
| 72 | + } |
| 73 | + return dp[i][j]; |
| 74 | + } |
| 75 | + |
| 76 | +} |
0 commit comments