You get an array nums of different positive numbers and a number target. Count the sequences of numbers from nums that add up to exactly target.
Each number may be used as many times as you like, and order matters: 1 + 3 and 3 + 1 are two different sequences. The answer fits in a 32-bit integer.
Example 1
Input: nums = [1, 3], target = 4 Output: 3 Why: 1+1+1+1, 1+3 and 3+1
2 more examples and the constraints
Example 2
Input: nums = [2, 4], target = 7 Output: 0 Why: sums of even numbers are never odd
Example 3
Input: nums = [5, 2, 3], target = 6 Output: 2 Why: 2+2+2 and 3+3; 5 leaves 1, which nothing makes
Constraints
- 1 ≤ nums.length ≤ 200
- 1 ≤ nums[i] ≤ 1,000, all different
- 1 ≤ target ≤ 1,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(target · n)
- Bottom-up tableO(target · n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for target 1,000 and 200 numbers | Verdict |
|---|---|---|---|
| Recursion with a memo | O(target · n) | Passes; recursion overhead | |
| Bottom-up table | O(target · n) | Best; two plain loops |
target = the sum to reach, n = length of nums.
Edge cases to test
- Every number too big. nums = [9] with target 3 gives 0: no number fits.
- Unreachable target. Only even numbers can never make an odd target; the table keeps those cells at 0.
- Big counts. [1, 2] with target 44 gives 1,134,903,170, close to the 32-bit limit. Counts for targets that are never used can overflow; in C++ use unsigned so that is safe.
- Unsorted input. The order of
numsdoes not matter; checkn ≤ tinstead of breaking out of the loop.
Common mistakes
- Putting nums in the outer loop, which counts 1 + 3 and 3 + 1 as one way.
- Starting with
dp[0] = 0, which makes every count 0. - Breaking out of the inner loop at the first n > t when nums is not sorted.
How to talk through it
- 1Clarify. Does order matter? Can a number repeat? Are all numbers positive?
- 2Find the recurrence. Fix the last number n: the rest is a sequence for t − n, so dp[t] sums dp[t − n].
- 3Mind the loop order. Target outside counts orderings; numbers outside would count combinations, as in Coin Change II.
- 4State the cost. O(target · n) time and O(target) space.
- 5Test out loud. Run a target no number reaches, and [1, 3] with target 4 to see that 1 + 3 and 3 + 1 both count.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?