Problems178
Search for a command to run...
Sort the candidates
Each candidate may be used at most once, and the input can repeat. Take a candidate and advance, or reject it and skip straight past all of its duplicates so no combination is built twice.
Sort + Skip Duplicates
1function func(ind, sum, nums, candidates, ans) {2 if (sum === 0) { ans.push([...nums]); return; }3 if (sum < 0 || ind === candidates.length) return;4 5 // Take candidates[ind], then move past it6 nums.push(candidates[ind]);7 func(ind + 1, sum - candidates[ind], nums, candidates, ans);8 nums.pop();9 10 // Reject it — and skip every duplicate of it11 for (let i = ind + 1; i < candidates.length; i++) {12 if (candidates[i] !== candidates[ind]) {13 func(i, sum, nums, candidates, ans);14 break;15 }16 }17}18 19function combinationSum2(candidates, target) {20 candidates.sort((a, b) => a - b);//candidates: [1,1,2,5,6]target: 821 const ans = [];22 func(0, target, [], candidates, ans);23 return ans;24}