Skip to content

Commit a984276

Browse files
committed
add solution for combination-sum
1 parent b84f940 commit a984276

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

combination-sum/Ujoonnee.java

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
import java.util.Stack;
4+
5+
class Solution {
6+
public List<List<Integer>> combinationSum(int[] candidates, int target) {
7+
List<List<Integer>> output = new ArrayList<>();
8+
Stack<Integer> nums = new Stack<>();
9+
dfs(candidates, output, nums, target, 0, 0);
10+
11+
return output;
12+
}
13+
14+
private void dfs(int[] candidates, List<List<Integer>> output, Stack<Integer> nums, int target, int start, int total) {
15+
if (total > target) {
16+
return;
17+
}
18+
if (total == target) {
19+
output.add(new ArrayList<>(nums));
20+
}
21+
for (int i=start; i<candidates.length; i++) {
22+
int num = candidates[i];
23+
nums.push(num);
24+
dfs(candidates, output, nums, target, i, total + num);
25+
nums.pop();
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)