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:
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?
刚开始写了个递归,就去提交了。
//这是错误的代码!
public int combinationSum4(int[] nums, int target) {
int len = nums.length;
Arrays.sort(nums);
int sum = 0;
for (int i = 0; i < len; i++) {
if (target - nums[i] > 0) sum += combinationSum4(nums, target - nums[i]);
if (target - nums[i] == 0) sum += 1;
if (target - nums[i] < 0) break;
}
return sum;
}
以上解法,毫无疑问,
Time Limit Exceeded了,因为很多步骤都是重复的,如 [1,50]的nums,target为200,所以根据这错的方法我们就会重复多计算比200小的target,导致超时,所以,我们要提前把比target小的数,都先计算出来,防止递归的时候,重复计算,导致超时。
public int combinationSum4(int[] nums, int target) {
Arrays.sort(nums);
int[] sum = new int[target + 1];
for (int i = 1; i <= target; i++) {//提前计算出所有小的target有几种组合数
for (int num : nums) {
if (i == num) sum[i] += 1;
if (i > num) sum[i] += sum[i - num];
if (i < num) break;
}
}
return sum[target];
}