LeetCode: Combination Sum II Solution
Backtracking with duplication checkImplementation
1var combinationSum2 = function (candidates, target) {2 const res = []34 const recursion = ({ candidates, remaining, combination }) => {5 if (remaining < 0) return67 if (remaining === 0) {8 res.push(combination)9 return10 }1112 candidates.forEach((candidate, i) => {13 if (i > 0 && candidate === candidates[i - 1]) return // duplication check1415 recursion({16 candidates: candidates.slice(i + 1), // a candidate must not be reused17 remaining: remaining - candidate,18 combination: [...combination, candidate],19 })20 })21 }2223 candidates.sort() // to help detect duplication while backtracking2425 recursion({26 candidates,27 remaining: target,28 combination: [],29 })3031 return res32}
References
Similar problems
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
LeetCode: Minimum Add to Make Parentheses Valid
Maintain balance, and yes, also naming variables
Previous Post
LeetCode: Top K Frequent Words
Hash and sort