LeetCode 377 Combination Sum IV

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];
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值