377. Combination Sum IV (Medium)
https://leetcode.com/problems/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?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
Solutions
class Solution {
// We must use below variable to record the number of combinations for a specific target.
// This approach really saves a great deal of time.
Map<Integer, Integer> combs = new HashMap<>();
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
// Here add LinkedList to track the elements that sums to target.
// Nevertheless, it's not necessary since this problem only requires the number of combinations.
return recurse(nums, target, new LinkedList<>());
}
private int recurse(int[] nums, int target, LinkedList<Integer> track) {
if (target == 0) {
// System.out.println(track);
return 1;
}
// No need to keep the track of elements that sums up to target
int ans = 0;
for (int i = 0; i < nums.length; i++) {
if (target < nums[i]) {
continue;
}
int nextRT = target - nums[i];
if (combs.containsKey(nextRT)) {
ans += combs.get(nextRT);
} else {
track.add(nums[i]);
int count = recurse(nums, nextRT, track);
track.removeLast();
ans += count;
combs.put(nextRT, count);
}
}
return ans;
}
}