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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit