leetcode icon indicating copy to clipboard operation
leetcode copied to clipboard

77. 组合

Open buuing opened this issue 4 years ago • 0 comments

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

示例:

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

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/combinations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。




  • 回溯算法
const combine = (n, k) => {
  const res = []
  const dfs = (map, arr, prev) => {
    if (arr.length === k) {
      return res.push(arr.slice())
    }
    for (let i = 1; i <= n; i++) {
      if (map[i] || prev > i) continue
      map[i] = 1
      arr.push(i)
      dfs(map, arr, i)
      arr.pop()
      map[i] = 0
    }
  }
  dfs([], [], 0)
  return res
}
  • 回溯算法 (优化版)
const combine = (n, k) => {
  const res = []
  const dfs = (arr, prev) => {
    if (arr.length === k) {
      return res.push(arr.slice())
    }
    for (let i = prev + 1; i <= n; i++) {
      arr.push(i)
      dfs(arr, i)
      arr.pop()
    }
  }
  dfs([], 0)
  return res
}

buuing avatar Dec 24 '20 16:12 buuing