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.
publicclassCombinationSumIV{ /* 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. */
// 可以,但是太耗时了。 staticint count = 0; publicstaticintcombinationSum4(int[] nums, int target){ List<ArrayList<Integer>> ans = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); dfs(nums, target, temp, 0); return count; } publicstaticvoiddfs(int[] nums, int target, ArrayList<Integer> temp, int k){ int sum = 0; for (int i: temp){ sum += i; } if (sum == target){ count ++; return ; } elseif (sum > target){ return ; } else { for (int i=0; i<nums.length; i++){ temp.add(nums[i]); dfs(nums, target, temp, k+1); temp.remove(temp.size()-1); } } }
publicstaticintcombinationSum4DP(int[] nums, int target){ if (target == 0){ return1; } int res = 0; for (int i=0; i<nums.length; i++){ if (target > nums[i]) res += combinationSum4DP(nums, target-nums[i]); } return res; }
publicstaticintcombinationSum4DPII(int[] nums, int target){
int[] dp = newint[target+1]; dp[0] = 1; for (int sum=1; sum<=target; sum++){ for (int i=0; i<nums.length; i++){ if (sum - nums[i] >=0) dp[sum] += dp[sum-nums[i]]; } } return dp[target]; }