|
1 |
| -/* |
2 |
| - Problem: https://leetcode.com/problems/combination-sum/ |
3 |
| - Description: return a list of all unique combinations of candidates where the chosen numbers sum to target |
4 |
| - Concept: Array, Backtracking |
5 |
| - Time Complexity: O(Nᵀ), Runtime 2ms |
6 |
| - Space Complexity: O(T), Memory 44.88MB |
7 |
| -*/ |
8 |
| -class Solution { |
9 |
| - public List<List<Integer>> answer = new ArrayList<>(); |
| 1 | +/** |
| 2 | + * <a href="https://leetcode.com/problems/combination-sum/">week03-3.combination-sum</a> |
| 3 | + * <li>Description: return a list of all unique combinations of candidates where the chosen numbers sum to target </li> |
| 4 | + * <li>Topics: Array, Backtracking </li> |
| 5 | + * <li>Time Complexity: O(K^T), Runtime 2ms </li> |
| 6 | + * <li>Space Complexity: O(T), Memory 44.9MB </li> |
| 7 | + */ |
10 | 8 |
|
| 9 | +class Solution { |
11 | 10 | public List<List<Integer>> combinationSum(int[] candidates, int target) {
|
| 11 | + List<List<Integer>> combinations = new ArrayList<>(); |
12 | 12 | Arrays.sort(candidates);
|
13 |
| - findCombination(candidates, target, new ArrayList<>(), 0); |
14 |
| - return answer; |
| 13 | + dfs(candidates, target, 0, new ArrayList<>(), combinations); |
| 14 | + return combinations; |
15 | 15 | }
|
16 | 16 |
|
17 |
| - public void findCombination(int[] candidates, int target, List<Integer> combination, int idx) { |
18 |
| - if(target == 0) { |
19 |
| - answer.add(new ArrayList<>(combination)); |
| 17 | + public void dfs(int[] candidates, int target, int index, List<Integer> combination, List<List<Integer>> combinations) { |
| 18 | + if (target == 0) { |
| 19 | + combinations.add(new ArrayList<>(combination)); |
20 | 20 | return;
|
21 | 21 | }
|
22 | 22 |
|
23 |
| - for(int i=idx; i<candidates.length; i++) { |
24 |
| - if(candidates[i] > target) break; |
| 23 | + for (int i = index; i < candidates.length; i++) { |
| 24 | + if (target - candidates[i] < 0) break; |
25 | 25 |
|
26 | 26 | combination.add(candidates[i]);
|
27 |
| - findCombination(candidates, target-candidates[i], combination, i); |
28 |
| - combination.remove(combination.size()-1); |
| 27 | + dfs(candidates, target - candidates[i], i, combination, combinations); |
| 28 | + combination.remove(combination.size() - 1); |
29 | 29 | }
|
30 | 30 | }
|
31 | 31 | }
|
0 commit comments