Given candidates (which may contain duplicates) and a target, return all unique combinations whose numbers sum to target. Each number may be used at most once.
Sort, then at each depth loop over the remaining candidates. Skip a value equal to the previous sibling (it would start the same combinations again) and stop once a value exceeds what is left.
1function combinationSum2(candidates: number[], target: number): number[][] {2candidates.sort((a, b) => a - b);3const res: number[][] = [], path: number[] = [];4function dfs(start: number, remain: number) {5if (remain === 0) { res.push([...path]); return; }6for (let i = start; i < candidates.length; i++) {7if (i > start && candidates[i] === candidates[i - 1]) continue;8if (candidates[i] > remain) break;9path.push(candidates[i]);10dfs(i + 1, remain - candidates[i]);11path.pop();12}13}14dfs(0, target);15return res;16}
Take 1; 7 left.
Space: play/pause · ←/→: step