Combination Sum II
2015-07-23 09:20
281 查看
Given a collection of candidate numbers (C) and a target number (T), find all unique
combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7] ,[1, 2, 5] ,[2, 6] ,[1, 1, 6]
与Combination Sum相比的唯一变化就是每个数字只能使用一次,这样在DFS中递归
下一个元素。同时不能有重复结果,可以先放到set中,再从set返回结果。
Combination Sum中没有这个处理也通过OJ,应该是测试用例没有考虑到这个问题。
combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7] ,[1, 2, 5] ,[2, 6] ,[1, 1, 6]
与Combination Sum相比的唯一变化就是每个数字只能使用一次,这样在DFS中递归
下一个元素。同时不能有重复结果,可以先放到set中,再从set返回结果。
Combination Sum中没有这个处理也通过OJ,应该是测试用例没有考虑到这个问题。
public static List<List<Integer>> combinationSum2(int[] candidates, int target) { ArrayList<List<Integer>> at=new ArrayList<List<Integer>>(); if(candidates==null||candidates.length<=0) return at; List<Integer> lt=new ArrayList<Integer>(); Arrays.sort(candidates); combinationSum2(candidates, target,0,at,lt); HashSet<List<Integer>> ht=new HashSet<List<Integer>>(at); at.clear(); at.addAll(ht); return at; } public static void combinationSum2(int[] arr,int target,int j,ArrayList<List<Integer>> at, List<Integer> lt){ if(target==0){ List<Integer> t=new ArrayList<Integer>(lt); at.add(t); return; } for(int i=j;i<arr.length;i++){ if(arr[i]>target) return; lt.add(arr[i]); combinationSum2(arr, target-arr[i], i+1, at, lt); lt.remove(lt.size()-1); } }
相关文章推荐
- Codeforces Round #313 (Div. 2)
- cxf+spring开发(一)--- 实现webservice简单输出实例
- Android实战简易教程-第二十四枪(基于Baas的用户表查询功能实现!)
- [转]2006 MySQL server has gone away错误,最大值溢出解决办法 mysql max_allowed_packet 查询和修改
- Android Studio 一些常用配置
- django 1.8 官方文档翻译: 2-5-4 聚合 (初稿)
- 2705 跳绳游戏
- Java 枚举变量解析
- (转)程序员秋季养生之道,今天你撸了吗?
- Sorting It All Out - poj 1094 (拓扑排序)
- Code::Block 'shared_ptr' was not declared in this scope
- Jmeter 图形结果分析
- Android基础入门教程——2.3.4 ImageView(图像视图)
- Storm-源码分析-LocalState (backtype.storm.utils)
- Problem A: Median Value
- POJ_1995_RaisingModuloNumbers
- js获取指定标签
- ORACLE 定时执行存储过程 <二>
- ;学习路线
- 在Django的视图(View)外使用Session的方法