Battery (Coin Change)

本文探讨了如何通过三种不同容量的电池(6节、9节、20节)组合来达到特定数量的需求,并提供了实现这一目标的算法解决方案。

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 }

 

转载于:https://www.cnblogs.com/superbo/p/4112172.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值