MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

kotlin/Backtracking/CombinationsOfSumK.kt:7–34  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

5}
6
7fun dfs(
8 combination: MutableList<Int>,
9 startIndex: Int,
10 nums: List<Int>,
11 target: Int,
12 res: MutableList<List<Int>>
13) {
14 // Termination condition: If the target is equal to 0, we found a combination
15 // that sums to 'k'.
16 if (target == 0) {
17 res.add(ArrayList(combination))
18 return
19 }
20 // Termination condition: If the target is less than 0, no more valid
21 // combinations can be created by adding it to the current combination.
22 if (target < 0) {
23 return
24 }
25 // Starting from start_index, explore all combinations after adding nums[i].
26 for (i in startIndex until nums.size) {
27 // Add the current number to create a new combination.
28 combination.add(nums[i])
29 // Recursively explore all paths that branch from this new combination.
30 dfs(combination, i, nums, target - nums[i], res)
31 // Backtrack by removing the number we just added.
32 combination.removeAt(combination.size - 1)
33 }
34}

Callers 1

combinationsOfSumKFunction · 0.70

Calls 1

addMethod · 0.45

Tested by

no test coverage detected