Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums toT.
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 基本一致,主要不同是不允许一个元素多次被使用。
JAVA代码:
- ArrayList<ArrayList<Integer> > res = new ArrayList<ArrayList<Integer>>();
- ArrayList<Integer> cur = new ArrayList<Integer>();
- void helper(int[] num,int target,int start) {
- if( start==num.length || target<=0) {
- if(target==0)
- res.add(new ArrayList<Integer>(cur));
- return;
- }
- for(int i=start;i<num.length;i++) {
- if(i > start && num[i] == num[i-1]) {
- continue;
- }
- cur.add(num[i]);
- helper(num,target-num[i],i+1);
- cur.remove(cur.size()-1);
- }
- }
- public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
- if(num==null) return res;
- Arrays.sort(num);
- helper(num,target,0);
- return res;
- }

浙公网安备 33010602011771号