FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

Day288:给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

Open Genzhen opened this issue 4 years ago • 1 comments

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

每日一题会在下午四点在交流群集中讨论,五点小程序中更新答案 欢迎大家在下方发表自己的优质见解

二维码加载失败可点击 小程序二维码

扫描下方二维码,收藏关注,及时获取答案以及详细解析,同时可解锁800+道前端面试题。

Genzhen avatar Apr 25 '21 04:04 Genzhen

const permute = function(n, k) {
  const res = []
  const used = {}

  const recursion = (path) => {
    if (path.length === k) {
      res.push(path)
      return
    }

    for (let i = 1; i <= n; i++) {
      if (used[i]) {
        continue
      }
      used[i] = true
      recursion([...path, i])
      used[i] = false
    }
  }

  recursion([])

  return res
};

DaphnisLi avatar Dec 28 '22 12:12 DaphnisLi