77. Combinations(js)

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
题意:给n个整数取k个数的所有可能
代码如下:
/**
 * @param {number} n
 * @param {number} k
 * @return {number[][]}
 */
var combine = function(n, k) {
    var res=new Set();
    var curr=new Set();
    backtrack(res,curr,n,k);
    return [...res];
};
var backtrack=function(res,curr,n,k){
    if(curr.size===k){
        res.add([...curr]);
    }else{
        for(var i=0;i<n;i++){
            if(curr.has(i+1)) continue;
            curr.add(i+1);
            backtrack(res,curr,i+1,k);
            curr.delete(i+1);
        }
    }
}

 

posted @ 2019-03-20 21:56  mingL  阅读(157)  评论(0编辑  收藏  举报