MEDIUM Blind #21 1-D Dynamic Programming
377. 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. Different sequences are counted as different combinations.
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขArray DP table updates
- โขState transition thinking
- โขBase case initialization
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Dynamic Programming reasoning pattern
๐ก Approach
- โ Use DP where dp[i] = number of combinations to sum to i
- โ For each target sum, consider adding each number from nums
- โ dp[i] = sum(dp[i - num] for all num in nums where num <= i)
- โ Base case: dp[0] = 1 (one way to make sum 0)
- โ Time: O(target * n), Space: O(target)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse DP where dp[i] = number of combinations to sum to i
- โขFor each target sum, consider adding each number from nums
- โขdp[i] = sum(dp[i - num] for all num in nums where num <= i)
Common Pitfalls
- โขBase case: dp[0] = 1 (one way to make sum 0)
- โขTime: O(target * n), Space: O(target)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
combinationSum3([1,2,3], 4); Expected:
4 Test Case 2
Not run Input:
combinationSum3([9], 3); Expected:
0 Test Case 3
Not run Input:
combinationSum3([2], 1); Expected:
0 ๐ Code Editor
๐ค Output