216. 组合总和 III

组合总和 III

解法一: 回溯

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func combinationSum3(k int, n int) [][]int {
ans := [][]int{}
var dfs func(cur, sum int, list []int)
dfs = func(cur, sum int, list []int) {
if len(list) == k && sum == n {
newList := make([]int, k)
copy(newList, list)
ans = append(ans, newList)
return
}
if cur > 9 || len(list) > k || sum > n {
return
}
for i := cur; i <= 9; i++ {
list = append(list, i)
sum += i
dfs(i+1, sum, list)
sum -= i
list = list[:len(list)-1]
}
}
dfs(1, 0, []int{})
return ans
}
作者

wuhunyu

发布于

2024-04-21

更新于

2025-01-15

许可协议