1import java.util.*;2
3class Solution {4 public List<List<Integer>> combinationSum(int[] candidates, int target) {5 List<List<Integer>> res = new ArrayList<>();6 Set<List<Integer>> seen = new HashSet<>();7 dfs(candidates, target, 0, new ArrayList<>(), res, seen);8 return res;9 }10
11 private void dfs(int[] candidates, int target, int total, List<Integer> path,12 List<List<Integer>> res, Set<List<Integer>> seen) {13 if (total == target) {14 15 List<Integer> key = new ArrayList<>(path);16 Collections.sort(key);17 if (seen.add(key)) res.add(key);18 return;19 }20 if (total > target) return;21 for (int c : candidates) {22 path.add(c);23 dfs(candidates, target, total + c, path, res, seen);24 path.remove(path.size() - 1);25 }26 }27}