Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

Follow up: What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?

  首先对于Follow up的考虑,如果数组中出现负数怎么办?应该对问题做一些什么限制?

Answer: 负数的出现导致的最大问题是无穷解。即由于负数的加入,导致可能某些数字的组合出现和为0,从而导致无限的0加入并不影响最终结果。

对于限制,如果正负Integer同时出现并且不限制数目的话,那么无法避免这中无限的情况。因为只要同时存在正负整数(a & b = -c),总可以找到a,c的公倍数导致 m x a + n x b = 0

唯一可能的限制就在于combination的长度。

Solution

这是一个有放回的抽取实验,可以使用递归来实现,it[target] = nums[i] + it[target-nums[i]], 但是如果target过大而nums过小,则容易导致栈溢出。

而且,递归并没有办法保存状态,重复计算的工作很多。

递归代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
public int combinationSum4(int[] nums, int target) {
if(target < 0)
return 0;
if(target == 0)
return 1;

int ret = 0;
for(int n: nums){
ret += combinationSum4(nums,target-n);
}
return ret;
}

没有意外,Submission Result: Time Limit Exceeded

更为有效的方式是使用动态规划,状态转移方程与递归类似: \[ dp_i = \sum dp[i-num_i] \] 代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int combinationSum4(int[] nums, int target) {
int [] dp = new int[target+1];
dp[0] = 1; //dp[i-i] = dp[0] = 1 make sure contains every number in array self.

for(int i = 1 ; i <= target; i ++){
for(int n:nums){
dp[i] += (i >= n) ? dp[i-n] : 0;
}
}
return dp[target];
}
}

参考Leetcode discuss可以做一些简单的优化。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class Solution {
public int combinationSum4(int[] nums, int target) {
Arrays.sort(nums);
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 1; i < res.length; i++) {
for (int num : nums) {
if (num > i)
break;
else
dp[i] += dp[i-num];
}
}
return dp[target];
}
}

即,先将nums数组排序,然后在for循环中break一些分支。