-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path377.组合总和-ⅳ.go
67 lines (64 loc) · 1.24 KB
/
377.组合总和-ⅳ.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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode.cn id=377 lang=golang
*
* [377] 组合总和 Ⅳ
*
* https://leetcode-cn.com/problems/combination-sum-iv/description/
*
* algorithms
* Medium (40.15%)
* Likes: 50
* Dislikes: 0
* Total Accepted: 2.3K
* Total Submissions: 5.7K
* Testcase Example: '[1,2,3]\n4'
*
* 给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
*
* 示例:
*
*
* nums = [1, 2, 3]
* target = 4
*
* 所有可能的组合为:
* (1, 1, 1, 1)
* (1, 1, 2)
* (1, 2, 1)
* (1, 3)
* (2, 1, 1)
* (2, 2)
* (3, 1)
*
* 请注意,顺序不同的序列被视作不同的组合。
*
* 因此输出为 7。
*
*
* 进阶:
* 如果给定的数组中含有负数会怎么样?
* 问题会产生什么变化?
* 我们需要在题目中添加什么限制来允许负数的出现?
*
* 致谢:
* 特别感谢 @pbrother 添加此问题并创建所有测试用例。
*
*/
func combinationSum4(nums []int, target int) int {
n := len(nums)
if n <= 0 {
return 0
}
dp := make([]int, target+1)
dp[0] = 1
for i := 1; i < target+1; i++ {
val := 0
for _, num := range nums {
if i >= num {
val += dp[i-num]
}
}
dp[i] = val
}
return dp[target]
}