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.這道題的意思是,輸入一個候選數字集(C)和一個目標數字(T).要求咱們找出C中的不一樣元素組合,使得這些元素加和等於T。要求C中的每個元素在一個組合中只能被使用一次。segmentfault
For example, 輸入候選數字集 [10, 1, 2, 7, 6, 1, 5] 和目標數字 8,
結果集應當是
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]code
public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> res = new ArrayList<List<Integer>>(); backtrack(res,new ArrayList<Integer>(),candidates,target,0); return res; } public void backtrack(List<List<Integer>> res,List<Integer> tempList,int[] candidates,int remain,int start){ if(remain < 0)return; if(remain == 0){ res.add(new ArrayList<>(tempList)); }else{ for(int i=start;i<candidates.length;i++){ if(i > start && candidates[i] == candidates[i-1]) continue; tempList.add(candidates[i]); backtrack(res,tempList,candidates,remain-candidates[i],i+1); tempList.remove(tempList.size()-1); } }