Skip to content

Commit d9dd5e0

Browse files
aQuaaQua
aQua
authored and
aQua
committed
216 accepted
1 parent 8725c6c commit d9dd5e0

File tree

3 files changed

+128
-0
lines changed

3 files changed

+128
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# [216. Combination Sum III](https://leetcode.com/problems/combination-sum-iii/)
2+
3+
## 题目
4+
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
5+
6+
Example 1:
7+
```
8+
Input: k = 3, n = 7
9+
Output: [[1,2,4]]
10+
```
11+
Example 2:
12+
```
13+
Input: k = 3, n = 9
14+
Output: [[1,2,6], [1,3,5], [2,3,4]]
15+
```
16+
17+
18+
Credits:Special thanks to @mithmatt for adding this problem and creating all test cases.
19+
20+
## 解题思路
21+
22+
见程序注释
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package Problem0216
2+
3+
func combinationSum3(k int, n int) [][]int {
4+
res := [][]int{}
5+
temp := make([]int, k+1)
6+
used := make([]bool, 10)
7+
8+
var dfs func(int, int)
9+
dfs = func(idx, remain int) {
10+
if idx == k {
11+
if remain < 10 && !used[remain] {
12+
temp[idx] = remain
13+
t := make([]int, k)
14+
copy(t, temp[1:])
15+
res = append(res, t)
16+
}
17+
return
18+
}
19+
20+
for i := temp[idx-1] + 1; i < 10; i++ {
21+
if remain-i < i {
22+
return
23+
}
24+
used[i] = true
25+
temp[idx] = i
26+
dfs(idx+1, remain-i)
27+
used[i] = false
28+
}
29+
}
30+
31+
dfs(1, n)
32+
33+
return res
34+
}
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package Problem0216
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type question struct {
11+
para
12+
ans
13+
}
14+
15+
// para 是参数
16+
type para struct {
17+
k int
18+
n int
19+
}
20+
21+
// ans 是答案
22+
type ans struct {
23+
one [][]int
24+
}
25+
26+
func Test_Problem0216(t *testing.T) {
27+
ast := assert.New(t)
28+
29+
qs := []question{
30+
31+
question{
32+
para{
33+
9,
34+
45,
35+
},
36+
ans{[][]int{
37+
[]int{1, 2, 3, 4, 5, 6, 7, 8, 9},
38+
}},
39+
},
40+
41+
question{
42+
para{
43+
3,
44+
7,
45+
},
46+
ans{[][]int{
47+
[]int{1, 2, 4},
48+
}},
49+
},
50+
51+
question{
52+
para{
53+
3,
54+
9,
55+
},
56+
ans{[][]int{
57+
[]int{1, 2, 6},
58+
[]int{1, 3, 5},
59+
[]int{2, 3, 4},
60+
}},
61+
},
62+
63+
// 如需多个测试,可以复制上方元素。
64+
}
65+
66+
for _, q := range qs {
67+
a, p := q.ans, q.para
68+
fmt.Printf("~~%v~~\n", p)
69+
70+
ast.Equal(a.one, combinationSum3(p.k, p.n), "输入:%v", p)
71+
}
72+
}

0 commit comments

Comments
 (0)