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); } } }