312. 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: * You may imagine nums[-1] = nums[n] = 1. They are not real therefore you can not burst them. * 0 ≤ n ≤ 500, 0 ≤ nums[i] ≤ 100 Example: Input: [3,1,5,8] Output: 167 Explanation: 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 Dfs + memo - > dp https://leetcode.com/problems/burst-balloons/discuss/76228/Share-some-analysis-and-explanations https://www.youtube.com/watch?v=z3hu2Be92UA&t=499s class Solution { public int maxCoins(int[] array) { int n = array.length; int[] nums = new int[n + 2]; for(int i = 0; i < array.length; i++){ nums[i + 1] = array[i]; } nums[0] = 1; nums[nums.length - 1] = 1; // dp[i][j] = maxCoins(nums[i : j + 1]) int[][] dp = new int[n + 2][n + 2]; // iterate thru the length from 1 to n for(int l = 1; l <= n; l++){ // starting point for the length of l for(int i = 1; i < n - l + 1; i++){ int j = i + l - 1; // iterate thru the middle breaking point for(int k = i; k <= j; k++){ dp[i][j] = Math.max(dp[i][j], dp[i][k -1] + dp[k + 1][j] + nums[i -1] * nums[k] * nums[j + 1]); } } } return dp[1][n]; } }
posted on 2018-11-08 16:33 猪猪🐷 阅读(136) 评论(0) 收藏 举报
浙公网安备 33010602011771号