递归:
var combine = function(n, k) {
const res = []
const recursion = (level, n, k, arr = []) => {
if (arr.length === k) {
res.push(arr);
return
}
if (level > n) return
recursion(level + 1, n, k, [...arr, level])
recursion(level + 1, n, k, arr)
}
recursion(1, n, k, [])
return res
};
var combine = function(n, k) {
const res = []
const recursion = (start, end = n, len = k, arr = []) => {
if (arr.length + (end - start + 1) < len) return
if (arr.length === len) {
res.push(arr);
return
}
recursion(start + 1, end, len, [...arr, start])
recursion(start + 1, end, len, arr)
}
recursion(1, n, k, [])
return res
};