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

Function dfs

python3/Backtracking/combinations_of_sum_k.py:9–27  ·  view source on GitHub ↗
(combination: List[int], start_index: int, nums: List[int], target: int,
        res: List[List[int]])

Source from the content-addressed store, hash-verified

7 return res
8
9def dfs(combination: List[int], start_index: int, nums: List[int], target: int,
10 res: List[List[int]]) -> None:
11 # Termination condition: If the target is equal to 0, we found a combination
12 # that sums to 'k'.
13 if target == 0:
14 res.append(combination[:])
15 return
16 # Termination condition: If the target is less than 0, no more valid
17 # combinations can be created by adding it to the current combination.
18 if target < 0:
19 return
20 # Starting from start_index, explore all combinations after adding nums[i].
21 for i in range(start_index, len(nums)):
22 # Add the current number to create a new combination.
23 combination.append(nums[i])
24 # Recursively explore all paths that branch from this new combination.
25 dfs(combination, i, nums, target - nums[i], res)
26 # Backtrack by removing the number we just added.
27 combination.pop()

Callers 1

combinations_of_sum_kFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected