216. Combination Sum III (JS)

题目意思:将n个分别放入k个容器,每个容器的存放数不能一样。
例如:Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
/*

  • @param {number} k个容器
  • @param {number} n个物品
  • @return {number[][]}
    */
    var combinationSum3 = function(k, n) {
    var nums = [];
    var ans = [];
    var j = 0;
    combinationSum(0,k,n);
    function combinationSum(last,count,sum)
    {
    if(sum==0 && count==0)
    {
    ans[j] = nums.concat();
    j++;
    return;
    }
    var end = sum<9?sum:9;
    end -= count-1;
    for(var i=last+1;i<=end;++i)
    {
    nums.push(i);
    combinationSum(i,count-1,sum-i);
    nums.pop();
    }
    }
    return ans;
    };

你可能感兴趣的:(216. Combination Sum III (JS))