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 30 31 32 33
| class Solution{ List<List<Integer>> result = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); int total = 0; Set<String> set = new HashSet<>(); public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); dfs(0, candidates, target); return result; } public void dfs(int begin, int[] candidates, int target){ if(target == 0){ List<Integer> ans = new ArrayList<>(tmp); if(!set.contains(ans.toString())){ set.add(ans.toString()); result.add(ans); } return; } for(int i = begin; i < candidates.length; i++){ if(target - candidates[i] < 0){ break; } tmp.add(candidates[i]); dfs(i + 1, candidates, target - candidates[i]); tmp.remove(tmp.size() - 1); } } }
|