Skip to content

Commit 767ed0f

Browse files
committed
add: CombinationsOfSumK
1 parent 085ab5a commit 767ed0f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
public class CombinationsOfSumK {
5+
public List<List<Integer>> combinationsOfSumK(int[] nums, int target) {
6+
List<List<Integer>> result = new ArrayList<>();
7+
dfs(new ArrayList<>(), 0, nums, target, result);
8+
return result;
9+
}
10+
11+
private void dfs(List<Integer> combination, int startIndex, int[] nums, int target, List<List<Integer>> result) {
12+
// Termination condition: If the target is equal to 0, we found a combination
13+
// that sums to 'k'.
14+
if (target == 0) {
15+
result.add(new ArrayList<>(combination));
16+
return;
17+
}
18+
// Termination condition: If the target is less than 0, no more valid
19+
// combinations can be created by adding it to the current combination.
20+
if (target < 0) {
21+
return;
22+
}
23+
// Starting from start_index, explore all combinations after adding nums[i].
24+
for (int i = startIndex; i < nums.length; i++) {
25+
// Add the current number to create a new combination.
26+
combination.add(nums[i]);
27+
// Recursively explore all paths that branch from this new combination.
28+
dfs(combination, i, nums, target - nums[i], result);
29+
// Backtrack by removing the number we just added.
30+
combination.remove(combination.size() - 1);
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)