public List<List<Integer>> combinationSum2(int[] candidates, int target) { backtrace(candidates, target, new ArrayList<>(), 0, 0); returnnew ArrayList<>(res); }
private Set<List<Integer>> res = new HashSet<>(); publicvoidbacktrace(int[] candidates, int target, List<Integer> path, int index, int sum){ //结束条件:路径中的和等于target if (sum == target){ ArrayList<Integer> re = new ArrayList<>(path); Collections.sort(re); res.add(re); return ; } for (int i = index; i < candidates.length; i++) { //剪枝 if (sum > target) return ; //做选择 sum += candidates[i]; path.add(candidates[i]); //递归 backtrace(candidates, target, path, i + 1, sum); //撤销 sum -= candidates[i]; path.remove(path.size() - 1); } }