# 77. 组合

# 描述

给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。

你可以按 任何顺序 返回答案。

示例 1:

输入:n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

示例 2:

输入:n = 1, k = 1
输出:[[1]]

提示:

  • 1 <= n <= 20
  • 1 <= k <= n

链接:https://leetcode.cn/problems/combinations

# 解答

const combine = (n, k) => {
  const res = [];

  const helper = (startIndex, path) => { //startIndex表示搜索的起点位置 path是每条分支的一个组合)
    if (path.length == k) {
      res.push(path.slice());       //需要拷贝一份 避免受其他分支的影响
      return;                       
    }
    for (let i = startIndex; i <= n - (k - path.length) + 1; i++) {//剪枝
      path.push(i);                    //加入path
      helper(i + 1, path);             //下一层递归
      path.pop();                      //回溯状态
    }
  };

  helper(1, []); //递归入口
  return res;
}

console.log(combine(13, 3));
本章目录