|
1 | 1 | class Solution {
|
2 | 2 | public List<List<Integer>> combinationSum2(int[] candidates, int target) {
|
3 |
| - List<List<Integer>> list = new ArrayList<>(); |
| 3 | + List<List<Integer>> result = new ArrayList<>(); |
4 | 4 | Arrays.sort(candidates);
|
5 |
| - helper(candidates, 0, target, new ArrayList<>(), list); |
6 |
| - return list; |
| 5 | + helper(candidates, target, result, new ArrayList<>(), 0); |
| 6 | + return result; |
7 | 7 | }
|
8 | 8 |
|
9 |
| - private void helper(int[] candidates, int idx, int target, List<Integer> temp, List<List<Integer>> list) { |
10 |
| - if (target == 0) { |
11 |
| - list.add(new ArrayList<>(temp)); |
12 |
| - return; |
13 |
| - } |
14 |
| - if (target < 0) { |
| 9 | + private void helper(int[] candidates, int target, List<List<Integer>> result, List<Integer> currCombination, int idx) { |
| 10 | + if (target <= 0) { |
| 11 | + if (target == 0) { |
| 12 | + result.add(new ArrayList<>(currCombination)); |
| 13 | + } |
15 | 14 | return;
|
16 | 15 | }
|
17 | 16 | for (int i = idx; i < candidates.length; i++) {
|
18 |
| - if (i > idx && candidates[i] == candidates[i - 1]) { |
| 17 | + if (i > idx && candidates[i] == candidates[i - 1]) { |
19 | 18 | continue;
|
20 | 19 | }
|
21 |
| - temp.add(candidates[i]); |
22 |
| - helper(candidates, i + 1, target - candidates[i], temp, list); |
23 |
| - temp.remove(temp.size() - 1); |
| 20 | + currCombination.add(candidates[i]); |
| 21 | + helper(candidates, target - candidates[i], result, currCombination, i + 1); |
| 22 | + currCombination.remove(currCombination.size() - 1); |
24 | 23 | }
|
25 | 24 | }
|
26 | 25 | }
|
0 commit comments