Combination Sum
Backtracking
Problem
Given an array of distinct integers candidates
and a target integer target
, return a list of all unique combinations of candidates
where the chosen numbers sum to target
. You may return the combinations in any order.
The same number may be chosen from candidates
an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.
It is guaranteed that the number of unique combinations that sum up to target
is less than 150
combinations for the given input.
For example:
Thought Process
When target == 0 is when we append to the solution list and backtrack. We also backtrack when target < 0, as this means the number we subtracted was too big and this number will not be a part of our solution set.
Since the same number can be used an unlimited amount, in our for loop we just keep looping with "i" being the index. This accomodates for the same number being able to be used unlimited amounts.
Why this works is because we pop the element at the end and the "i" increments anyways in our for loop so this searches through the other numbers as well even though we aren't directly incrementing the pointer in our recursion.
Solution
Key Points
Using the for-loop, in our recursion method we can use "i" as the index to account for the number being used multiple times.
f
"Tagret - candidates[i]" is what we use in our recursion method and what we use to stop DFS/begin backtracking when target == 0 or target < 0.
Time Complexity
Last updated
Was this helpful?