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 - Dynamic Programming INPUT nums array: 1 2 3 [0] [1] [2] target: 4 Find all sequences that sum to target. [1,2] and [2,1] are different combinations nums=[1,2,3], target=4 ALGORITHM STEPS 1 Initialize DP Array dp[0]=1, dp[1..4]=0 2 Loop i from 1 to target For each sum value 3 For each num in nums if i>=num: dp[i]+=dp[i-num] 4 Return dp[target] Answer is dp[4] DP Table: 1 dp[0] 1 dp[1] 2 dp[2] 4 dp[3] 7 dp[4] dp[i] = sum(dp[i-num]) FINAL RESULT Number of combinations: 7 All 7 combinations: [1,1,1,1] [1,1,2], [1,2,1], [2,1,1] [2,2] [1,3], [3,1] Output: 7 OK - Result Verified Key Insight: Unlike standard combination sum, order matters here (permutations). dp[i] counts all ordered sequences summing to i. For each target sum i, we add ways to reach (i - num) for each num. Time: O(target * n), Space: O(target). Base case dp[0]=1 represents empty sequence. TutorialsPoint - Combination Sum IV | Dynamic Programming Approach
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