Given distinct integers candidates and a target, return all unique combinations of candidates that sum to target. The same number may be chosen any number of times.
Build combinations in non-decreasing index order so each set is generated once. Reuse the same index to allow repeats, and stop early once a candidate overshoots (they are sorted).
1function combinationSum(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 (candidates[i] > remain) break;8path.push(candidates[i]);9dfs(i, remain - candidates[i]);10path.pop();11}12}13dfs(0, target);14return res;15}
Sort the candidates so we can prune.
Space: play/pause · ←/→: step