# LeetCode: Combination Sum II Solution

Backtracking with duplication check

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var combinationSum2 = function (candidates, target) {2  const res = []3
4  const recursion = ({ candidates, remaining, combination }) => {5    if (remaining < 0) return6
7    if (remaining === 0) {8      res.push(combination)9      return10    }11
12    candidates.forEach((candidate, i) => {13      if (i > 0 && candidate === candidates[i - 1]) return // duplication check14
15      recursion({16        candidates: candidates.slice(i + 1), // a candidate must not be reused17        remaining: remaining - candidate,18        combination: [...combination, candidate],19      })20    })21  }22
23  candidates.sort() // to help detect duplication while backtracking24
25  recursion({26    candidates,27    remaining: target,28    combination: [],29  })30
31  return res32}```

Original problem

Combination Sum

leetcode

recursion

backtracking

## Next Post

LeetCode: Minimum Add to Make Parentheses Valid

Oct 26, 2022

Maintain balance, and yes, also naming variables

## Previous Post

LeetCode: Top K Frequent Words

Oct 19, 2022

Hash and sort

Search Posts