-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcombinations.js
More file actions
47 lines (44 loc) · 883 Bytes
/
Copy pathcombinations.js
File metadata and controls
47 lines (44 loc) · 883 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 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],
// ]
//
//
/**
* @param {number} n
* @param {number} k
* @return {number[][]}
*/
var combine = function(n, k) {
var result = [],
current = [],
used = [];
var _r = function(dep, len) {
if (len >= k) {
result.push([].concat(current));
return ;
}
for (var i = dep;i <= n;++i) {
if (!used[i]) {
used[i] = true;
current.push(i);
_r(i+1, len+1);
current.pop();
used[i] = false;
}
}
};
_r(1, 0);
return result;
};