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
A solution set is:
10,1,2,7,6,1,5
and target 8
,A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Solution: O(n^2)
public class Solution { public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) { Arrays.sort(num); ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<Integer>(); getlist(num,target,list,ret,0); return ret; } public void getlist(int[] num, int target, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> ret,int start){ if(target == 0){ ArrayList<Integer> t = new ArrayList<Integer>(list); if(!ret.contains(t)) ret.add(t); return; } for(int i=start; i<num.length; i++){ if(target-num[i]>=0){ list.add(num[i]); getlist(num,target-num[i],list,ret,i+1); list.remove(list.size()-1); }else break; } } }
沒有留言:
張貼留言