Problems178
Search for a command to run...
Initialization
Find every set of exactly 3 distinct digits from 1–9 that sums to 7. Because each call starts from one past the digit just used, combinations come out sorted and never repeat.
Backtracking with Pruning
1function func(sum, last, nums, k, ans) {2 // Exactly k digits and the target hit3 if (sum === 0 && nums.length === k) {4 ans.push([...nums]);5 return;6 }7 8 // Overshot the sum, or used too many digits9 if (sum <= 0 || nums.length > k) return;10 11 for (let i = last; i <= 9; i++) {12 if (i <= sum) {13 nums.push(i);14 func(sum - i, i + 1, nums, k, ans);15 nums.pop();16 } else {17 // Digits only grow — nothing later can fit18 break;19 }20 }21}22 23function combinationSum3(k, n) {24 const ans = [];25 const nums = [];26 func(n, 1, nums, k, ans);//k: 3n: 727 return ans;28}