Combination Sum IV - Problem

Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.

The test cases are generated so that the answer can fit in a 32-bit integer.

Note: Different sequences are counted as different combinations. For example, [1,2] and [2,1] are considered different combinations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3], target = 4
Output: 7
💡 Note: The possible combinations are: [1,1,1,1], [1,1,2], [1,2,1], [2,1,1], [1,3], [3,1], [2,2]. Total of 7 combinations.
Example 2 — Single Element
$ Input: nums = [9], target = 3
Output: 0
💡 Note: Since 9 > 3, there's no way to form target 3 using only number 9. Answer is 0.
Example 3 — Perfect Match
$ Input: nums = [1,2], target = 3
Output: 3
💡 Note: The possible combinations are: [1,1,1], [1,2], [2,1]. Total of 3 combinations.

Constraints

  • 1 ≤ nums.length ≤ 200
  • 1 ≤ nums[i] ≤ 1000
  • All elements in nums are unique
  • 1 ≤ target ≤ 1000

Visualization

Tap to expand
Combination Sum IV: Find Number of Waysnums = [1, 2, 3], target = 4Possible Ways:1. [1,1,1,1] = 42. [1,1,2] = 43. [1,2,1] = 44. [2,1,1] = 45. [1,3] = 46. [3,1] = 47. [2,2] = 4Key Insight:Order matters![1,2,1] ≠ [2,1,1]Count all sequencesthat sum to targetUse DP to avoidrecalculatingAnswer: 7 combinationsTime: O(target × nums.length), Space: O(target)
Understanding the Visualization
1
Input
Array nums=[1,2,3] and target=4
2
Find Combinations
Count all sequences that sum to target
3
Output
Return total count of combinations
Key Takeaway
🎯 Key Insight: This is an unbounded knapsack where order matters - use DP to count all possible sequences
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
380.0K Views
Medium Frequency
~25 min Avg. Time
4.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen