101 Logo
onenoughtone

Problem Statement

Combination Sum IV

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.

Examples

Example 1:

Input: nums = [1,2,3], target = 4
Output: 7
Explanation: The possible combination ways are: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) Note that different sequences are counted as different combinations.

Example 2:

Input: nums = [9], target = 3
Output: 0
Explanation: There are no combinations that sum to target.

Constraints

  • 1 <= nums.length <= 200
  • 1 <= nums[i] <= 1000
  • All the elements of nums are unique
  • 1 <= target <= 1000

Problem Breakdown

To solve this problem, we need to:

  1. This problem can be solved using dynamic programming.
  2. The key insight is to define dp[i] as the number of ways to form the sum i using the given numbers.
  3. For each number num in nums, if i >= num, then dp[i] += dp[i - num].
  4. The base case is dp[0] = 1, as there is one way to form the sum 0 (by not selecting any number).
  5. The problem is similar to the coin change problem, but the order of elements matters here.
ProblemSolutionCode
101 Logo
onenoughtone