Combination Sum IV

Given an array of distinct positive integers nums and a target, return how many ordered sequences of numbers from nums add up to target. A number may be used any number of times, and different orders count as different sequences, so (1, 2) and (2, 1) are two answers. The answer fits in a 32-bit integer.

30:00

Combination Sum IV
medium
Free written solution
Topics
Companies

Given an array of distinct positive integers nums and a target, return how many ordered sequences of numbers from nums add up to target. A number may be used any number of times, and different orders count as different sequences, so (1, 2) and (2, 1) are two answers. The answer fits in a 32-bit integer.

Example 1:
Input: {"nums":[1,2,3],"target":4}
Output: 7
Constraints:
  • 1≤nums.length≤2001 \leq \text{nums.length} \leq 200

  • 1≤nums[i]≤10001 \leq \text{nums}[i] \leq 1000

  • All the elements of nums are unique.

  • 1≤target≤10001 \leq \text{target} \leq 1000

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3],"target":4}

nums

1
2
3

target 4

dp[i] will count the ordered sequences that sum to i. dp[0] = 1: the empty sequence is the one way to make 0.

dp[i] = number of ordered sequences summing to i

10?1?2?3?4

sequences

dp[0] = 1 counts the empty sequence ( )

Variables
VariableValue
total0
dp[total]1
DepthFunction Call
Stack empty
0/17