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

Function dfs

cpp/Backtracking/combinations_of_sum_k.cpp:10–31  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8}
9
10void dfs(std::vector<int>& combination, int startIndex, std::vector<int>& nums, int target, std::vector<std::vector<int>>& res) {
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.push_back(combination);
15 return;
16 }
17 // Termination condition: If the target is less than 0, no more valid
18 // combinations can be created by adding it to the current combination.
19 if (target < 0) {
20 return;
21 }
22 // Starting from startIndex, explore all combinations after adding nums[i].
23 for (int i = startIndex; i < nums.size(); i++) {
24 // Add the current number to create a new combination.
25 combination.push_back(nums[i]);
26 // Recursively explore all paths that branch from this new combination.
27 dfs(combination, i, nums, target - nums[i], res);
28 // Backtrack by removing the number we just added.
29 combination.pop_back();
30 }
31}

Callers 1

combinationsOfSumKFunction · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected