1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| class Solution { List<List<Integer>> ans = new ArrayList<>(); List<Integer> path = new ArrayList<>(); int[] candidates;
public List<List<Integer>> combinationSum2(int[] candidates, int target) { this.candidates = candidates; Arrays.sort(candidates); dfs(0, target); return ans; }
private void dfs(int start, int target) { if (target == 0) { ans.add(new ArrayList<>(path)); return; } for (int i = start; i < candidates.length; ++i) { if (target - candidates[i] < 0) break; if (i > start && candidates[i] == candidates[i - 1]) continue; path.add(candidates[i]); dfs(i + 1, target - candidates[i]); path.remove(path.size() - 1); } } }
|