39. Combination Sum
Given a set of candidate numbers and a target number, find all unique combinations in the set that sum to the target.
Approach: Backtracking
Algorithm:
- Initialize an empty list to store the result.
- Define a recursive function that takes the current index, remaining target, and the current path.
- If the remaining target is 0, add the current path to the result.
- If the remaining target is negative, return.
- Iterate through the candidates starting from the current index.
- Add each candidate to the current path and recursively call the function with updated parameters.
- Remove the last added candidate from the path (backtrack).
- Return the result.
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
ans = []
def backtracking(start, target, path):
if target == 0:
ans.append(list(path))
return
if target < 0:
return
for i in range(start, len(candidates)):
path.append(candidates[i])
backtracking(i, target-candidates[i], path)
path.pop()
backtracking(0, target, [])
return ans- Time: — In the worst case, we might have to explore all possible combinations.
- Space: — The maximum depth of the recursion tree is the target value.
Last updated on