[
dp
backtracking
dfs
]
Leetcode 0039. Combination Sum
https://leetcode.com/problems/combination-sum
This is classical backtracking problem, so let us use BackTr(target, curr_sol, k)
function, where:
target
is target we need to build, if we get some number, we subtract if from target.curr_sol
is current solution built so far.k
is index in ourcandidates
: each new number we take should have number more or equal thank
.
So, no in algorighm we do:
- If
target == 0
, it means we found solution, which is kept incurr_sol
, so we add it toself.sol
list of all found solutions. - If
target
if negative ork
is more than number of candidates, we need to go back. - Finally, for each candidate index in
k,...
, we run our function recursively with updated parameters.
Complexity: TBD
class Solution:
def combinationSum(self, candidates, target):
def BackTr(target, curr_sol, k):
if target == 0:
self.sol.append(curr_sol)
if target < 0 or k >= len(candidates):
return
for i in range(k, len(candidates)):
BackTr(target - candidates[i], curr_sol + [candidates[i]], i)
self.sol = []
BackTr(target, [], 0)
return self.sol
If you like the solution, you can upvote it on leetcode discussion section: Problem 0039