Skip to content

Commit cbf710f

Browse files
committed
dfs: 组合
Change-Id: I313e44461de5977cbdfac717470bf5dc25531dff
1 parent 345ee92 commit cbf710f

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
* @lc app=leetcode.cn id=216 lang=golang
3+
*
4+
* [216] 组合总和 III
5+
*
6+
* https://leetcode-cn.com/problems/combination-sum-iii/description/
7+
*
8+
* algorithms
9+
* Medium (69.01%)
10+
* Likes: 71
11+
* Dislikes: 0
12+
* Total Accepted: 10.2K
13+
* Total Submissions: 14.8K
14+
* Testcase Example: '3\n7'
15+
*
16+
* 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
17+
*
18+
* 说明:
19+
*
20+
*
21+
* 所有数字都是正整数。
22+
* 解集不能包含重复的组合。 
23+
*
24+
*
25+
* 示例 1:
26+
*
27+
* 输入: k = 3, n = 7
28+
* 输出: [[1,2,4]]
29+
*
30+
*
31+
* 示例 2:
32+
*
33+
* 输入: k = 3, n = 9
34+
* 输出: [[1,2,6], [1,3,5], [2,3,4]]
35+
*
36+
*
37+
*/
38+
39+
// @lc code=start
40+
func combinationSum3(k int, n int) [][]int {
41+
out := []int{}
42+
res := [][]int{}
43+
dfs(k, n, 1, 10, &out, &res)
44+
return res
45+
}
46+
47+
func dfs(k int, n int, start int, end int, out *[]int, res *[][]int) {
48+
if k == 0 && n == 0 {
49+
*res = append(*res, append([]int{}, (*out)...))
50+
return
51+
}
52+
if k < 0 || n < 0 {
53+
return
54+
}
55+
for i := start; i < end; i++ {
56+
*out = append(*out, i)
57+
dfs(k-1, n-i, i+1, end, out, res)
58+
*out = (*out)[:len(*out)-1]
59+
}
60+
}
61+
// @lc code=end
62+

0 commit comments

Comments
 (0)