Back to Leetcode Go

77. Combinations

website/content/ChapterFour/0001~0099/0077.Combinations.md

1.7.11.4 KB
Original Source

77. Combinations

题目

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],
]

题目大意

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

解题思路

  • 计算排列组合中的组合,用 DFS 深搜即可,注意剪枝

代码

go

package leetcode

func combine(n int, k int) [][]int {
	if n <= 0 || k <= 0 || k > n {
		return [][]int{}
	}
	c, res := []int{}, [][]int{}
	generateCombinations(n, k, 1, c, &res)
	return res
}

func generateCombinations(n, k, start int, c []int, res *[][]int) {
	if len(c) == k {
		b := make([]int, len(c))
		copy(b, c)
		*res = append(*res, b)
		return
	}
	// i will at most be n - (k - c.size()) + 1
	for i := start; i <= n-(k-len(c))+1; i++ {
		c = append(c, i)
		generateCombinations(n, k, i+1, c, res)
		c = c[:len(c)-1]
	}
	return
}


<div style="display: flex;justify-content: space-between;align-items: center;"> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0076.Minimum-Window-Substring/">⬅️上一页</a></p> <p><a href="https://books.halfrost.com/leetcode/ChapterFour/0001~0099/0078.Subsets/">下一页➡️</a></p> </div>