classSolution{public List<List<Integer>>combinationSum2(int[] candidates,int target){
List<List<Integer>> res =newArrayList<>();
Arrays.sort(candidates);backTrack(res,newArrayList<>(), candidates, target,0);// Set<List<Integer>> set = new HashSet<>(res);// return new ArrayList<>(set);// 用set慢 因为set底层是红黑树return res;}publicvoidbackTrack(List<List<Integer>> res, List<Integer> temp,int[] candidates,int target,int start){if(target <0)return;if(target ==0){
res.add(newArrayList<>(temp));return;}for(int i = start; i < candidates.length; i++){if(target <0)break;// 去重关键步骤 ↓if(i > start && candidates[i]== candidates[i -1])continue;
temp.add(candidates[i]);backTrack(res, temp, candidates, target - candidates[i], i +1);
temp.remove(temp.size()-1);}}}
组合总和Ⅲ
classSolution{public List<List<Integer>>combinationSum3(int k,int n){
List<List<Integer>> res =newArrayList<>();combine(res,newArrayList<>(), k, n,1);return res;}publicvoidcombine(List<List<Integer>> res, List<Integer> temp,int k,int n,int start){if(temp.size()> k || n <0)return;if(n ==0&& temp.size()== k){
res.add(newArrayList<>(temp));return;}for(int i = start; i <= Math.min(n,9); i++){
temp.add(i);combine(res, temp, k, n - i, i +1);
temp.remove(temp.size()-1);}}}