LeetCode: Combination Sum Solution
Recursively try all the possible casesApproach
Exhausively try all the cases
combination
: store the list of candidates for each check
remaining
: check whether a combination
sum equals to target
Implementation
1var combinationSum = function (candidates, target) {2 const res = []34 const recursion = ({ candidates, remaining, combination }) => {5 if (remaining < 0) {6 return7 }8 if (remaining === 0) {9 res.push(combination)10 return11 }12 candidates.forEach((candidate, i) =>13 recursion({14 candidates: candidates.slice(i), // a candidate could be reused15 remaining: remaining - candidate,16 combination: [...combination, candidate],17 })18 )19 }2021 recursion({ candidates, remaining: target, combination: [] })2223 return res24}
References
Similar problems
Letter Combinations of a Phone Number
Combination Sum II
Combinations
Combination Sum III
Factor Combinations
Combination Sum IV
Comments
Loading comments...
Tags
leetcode
recursion
backtracking
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
The author is not smart enough to come up with the DP solution in the first place
Previous Post
Count non-zero unique numbers