Problem Description
Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target. Different sequences of the same numbers count as distinct combinations.
Key Insights
- Use dynamic programming to count the number of valid combinations.
- The order in which numbers are picked matters, making this akin to permutation counting.
- Initialize a DP table where dp[i] represents the number of ways to form the sum i.
- dp[0] is initialized to 1 since there is one way to form a sum of 0 (by choosing nothing).
- For each sum i from 1 to target, iterate over nums and update dp[i] based on dp[i - num] when i >= num.
- For negative numbers, the problem becomes unbounded due to potential infinite combinations; hence a constraint on the combination length is required to make it well-defined.
Space and Time Complexity
Time Complexity: O(target * n), where n is the length of nums. Space Complexity: O(target), for the dp array of size target + 1.
Solution
The problem is solved using a bottom-up dynamic programming approach. We create a dp array where each dp[i] represents the number of possible combinations to reach the sum i. We iterate from 1 up to target, and for each sum, we check every number in nums. If the number can contribute to the current sum (i - num >= 0), we add the number of ways to form the remainder (i - num) to dp[i]. This ensures that every possible permutation is counted. When negative numbers are allowed in the input, the potential for an infinite number of combinations arises unless we impose additional constraints, such as limiting the length of the combination.