首页 > 其他 > 详细

Burst Balloons

时间:2016-07-24 07:00:43      阅读:209      评论:0      收藏:0      [点我收藏+]

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

Given [4, 1, 5, 10]
Return 270

nums = [4, 1, 5, 10] burst 1, get coins 4 * 1 * 5 = 20
nums = [4, 5, 10]    burst 5, get coins 4 * 5 * 10 = 200 
nums = [4, 10]       burst 4, get coins 1 * 4 * 10 = 40
nums = [10]          burst 10, get coins 1 * 10 * 1 = 10

Total coins 20 + 200 + 40 + 10 = 270

递归做法:
 1 public class Solution {
 2     /**
 3      * @param nums a list of integer
 4      * @return an integer, maximum coins
 5      */
 6     public int maxCoins(int[] nums) {
 7         // Write your code here
 8         if (nums == null || nums.length == 0)
 9             return 0;
10 
11         ArrayList<Integer> list = new ArrayList<Integer>();
12         for (int index = 0; index < nums.length; index++) {
13             list.add(nums[index]);
14         }
15         return helper(list);
16     }
17 
18     public int helper(ArrayList<Integer> list) {
19         if (list.size() == 1) {
20             return list.get(0);
21         }
22 
23         int max = 0;
24         for (int i = 0; i < list.size(); i++) {
25             int value = 0;
26             if (i == 0) {
27                 value = list.get(0) * list.get(1);
28             } else if (i == list.size() - 1) {
29                 value = list.get(i - 1) * list.get(i);
30             } else {
31                 value = list.get(i - 1) * list.get(i) * list.get(i + 1);
32             }
33             ArrayList<Integer> temp = new ArrayList<Integer>(list);
34             temp.remove(i);
35 
36             max = Math.max(max, value + helper(temp));
37         }
38         return max;
39     }
40 } 

 

 

 

Burst Balloons

原文:http://www.cnblogs.com/beiyeqingteng/p/5700023.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!