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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
class Solution { public int combinationSum4(int[] nums, int target) { int[] res = new int[1]; help(res, new ArrayList(), nums, target, 0); return res[0]; } public void help(int[] res, List<Integer> cur, int[] nums, int target, int sum) { if(sum > target) return; if(sum == target) { res[0]++; return; } for(int i = 0; i < nums.length; i++) { sum += nums[i]; cur.add(nums[i]); help(res, cur, nums, target, sum); sum -= nums[i]; cur.remove(cur.size() - 1); } } }
TLE了,屮
class Solution { public int combinationSum4(int[] nums, int target) { if (target == 0) { return 1; } int res = 0; for (int i = 0; i < nums.length; i++) { if (target >= nums[i]) { res += combinationSum4(nums, target - nums[i]); } } return res; } }
这个也是递归,也tle了。
仔细看一下,和coin change2十分相似,都是从中间态得到最终结果,那就是个dp,还是初始化dp【0】 = 1
class Solution { public int combinationSum4(int[] nums, int target) { int[] comb = new int[target + 1]; comb[0] = 1; for (int i = 1; i < comb.length; i++) { for (int j = 0; j < nums.length; j++) { if (i - nums[j] >= 0) { comb[i] += comb[i - nums[j]]; } } } return comb[target]; } }
看清楚需求,这个包括了重复的,所以coin在inner loop