Question:
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example:
Input: k = 3, n = 7
Output: [[1,2,4]]
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
Solution:
/**
* @param {number} k
* @param {number} n
* @return {number[][]}
*/
var combinationSum3 = function(k, n) {
const result = [];
let dfs = function (num, path, fromNum) {
if (num === 0 && path.length === k) {
result.push(path);
}
if (path.length < k) {
for ( let i = fromNum; i < 10; i++) {
let nextPath = Object.assign([],path);
nextPath.push(i);
dfs(num-i,nextPath,i+1);
}
}
}
//递归调用
dfs(n,[],1);
return result;
};
Runtime: 56 ms, faster than 55.65% of JavaScript online submissions for Combination Sum III.