码迷,mamicode.com
首页 > 其他好文 > 详细

Battery (Coin Change)

时间:2014-11-21 10:32:15      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   strong   on   

Problem

电池有6节包装,9节包装,20节包装三种,input需要多少节电池,如果可以刚好用3种包装的凑到这个数,就输出这个解, 忘了是不是要输出所有的解。
e.g 输入20, 答{20} 输入17 答没有 输入18,那可能是{6,6,6}也可能是{9,9}。 有点像找钱的问题,似乎是从集合中找到所有集合值等于一个target这个题的简化版,因为集合只有6 9 20。

Solution

 1 public static List<List<Integer>> combination(int[] num, int target) {
 2     List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     
 4     if(num == null || num.length == 0) return res;
 5     
 6     List<Integer> path = new ArrayList<Integer>();
 7     helper(num, target, res, path);
 8     return res;
 9         
10 }
11 
12 public static void helper(int[] num, int target, List<List<Integer>> res, List<Integer> path) {
13     
14     if(target == 0) {
15         res.add(new ArrayList<Integer>(path));
16         return;
17     }
18     
19     if(target < 0)
20         return;
21 
22     for(int i=0; i<num.length; i++) {
23         path.add(num[i]);
24         helper(num, target - num[i], res, path);
25         path.remove(path.size() - 1);
26     }
27 }

 

Battery (Coin Change)

标签:style   blog   io   ar   color   sp   for   strong   on   

原文地址:http://www.cnblogs.com/superbo/p/4112172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!