Skip to content

Commit 5bf74c8

Browse files
authored
feat: combination sum
1 parent 6e4c3ab commit 5bf74c8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

combination-sum/minji-go.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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(N), Memory 44.88MB
7+
8+
- Time Complexity, Space Complexity를 어떻게 계산해야할지 어렵네요 :(
9+
*/
10+
class Solution {
11+
public List<List<Integer>> answer = new ArrayList<>();
12+
13+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
14+
Arrays.sort(candidates);
15+
findCombination(candidates, target, new ArrayList<>(), 0);
16+
return answer;
17+
}
18+
19+
public void findCombination(int[] candidates, int target, List<Integer> combination, int idx) {
20+
if(target == 0) {
21+
answer.add(new ArrayList<>(combination));
22+
return;
23+
}
24+
25+
for(int i=idx; i<candidates.length; i++) {
26+
if(candidates[i] > target) break;
27+
28+
combination.add(candidates[i]);
29+
findCombination(candidates, target-candidates[i], combination, i);
30+
combination.remove(combination.size()-1);
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)