Skip to content

Commit 65cb45e

Browse files
committed
dfs: 组合
Change-Id: Ib9e0541639054882b8121210e76e99d253c3f71b
1 parent 2b7f471 commit 65cb45e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

go/leetcode/77.组合.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*
2+
* @lc app=leetcode.cn id=77 lang=golang
3+
*
4+
* [77] 组合
5+
*
6+
* https://leetcode-cn.com/problems/combinations/description/
7+
*
8+
* algorithms
9+
* Medium (68.47%)
10+
* Likes: 125
11+
* Dislikes: 0
12+
* Total Accepted: 12.8K
13+
* Total Submissions: 18.6K
14+
* Testcase Example: '4\n2'
15+
*
16+
* 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
17+
*
18+
* 示例:
19+
*
20+
* 输入: n = 4, k = 2
21+
* 输出:
22+
* [
23+
* ⁠ [2,4],
24+
* ⁠ [3,4],
25+
* ⁠ [2,3],
26+
* ⁠ [1,2],
27+
* ⁠ [1,3],
28+
* ⁠ [1,4],
29+
* ]
30+
*
31+
*/
32+
33+
// @lc code=start
34+
func combine(n int, k int) [][]int {
35+
out := []int{}
36+
res := [][]int{}
37+
dfs(n, k, &out, &res)
38+
return res
39+
}
40+
41+
func dfs(n int, k int, out *[]int, res *[][]int) {
42+
if k <= 0 {
43+
*res = append(*res, append([]int{}, (*out)...))
44+
return
45+
}
46+
for i := n; i > 0; i-- {
47+
*out = append(*out, i)
48+
dfs(i-1, k-1, out, res)
49+
*out = (*out)[:len(*out)-1]
50+
}
51+
}
52+
// @lc code=end
53+

0 commit comments

Comments
 (0)