LeetCode377-组合总和IV

题目链接

英文链接:https://leetcode.com/problems/combination-sum-iv/

中文链接:https://leetcode-cn.com/problems/combination-sum-iv/

题目详述

给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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。

进阶:
如果给定的数组中含有负数会怎么样?
问题会产生什么变化?
我们需要在题目中添加什么限制来允许负数的出现?

题目详解

  • 完全背包问题。
  • 需要注意,顺序不同的序列被视作不同的组合,所以需要先枚举容量,保留顺序信息。

  • dp[i] 表示目标数为 i 时的个数。

  • dp[0] = 1。
  • dp[i] = dp[i - num[0]] + ... + dp[i - num[nums.length - 1]]如果下标未越界
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LeetCode_00377 {

public int combinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (int num : nums) {
if (i >= num) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
}