77. Combinations
发布时间:2020-12-14 04:36:36 所属栏目:大数据 来源:网络整理
导读:77.?Combinations Given two integers? n ?and? k ,return all possible combinations of? k ?numbers out of 1 ...? n . Example: Input:?n = 4,k = 2Output:[ [2,4],[3,[2,3],[1,2],] 题意:给n个整数取k个数的所有可能 代码如下: /* * * @param {number}
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,[2,3],[1,2],] /** * @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,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,i+1,k); curr.delete(i+1); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |