Leetcode 377. 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 the target.
The order of the numbers in the combination matters.
You may assume that the same number can be used an unlimited number of times.
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)
Example 2:
Input: nums = [9], target = 3
Output: 0
nums
or the value of target
?
This problem can be tackled using Dynamic Programming (DP). The idea here is to build a dp array where each element at index i
represents the number of combinations that sum up to i
.
target + 1
with dp[0] = 1
, because there is one way to reach 0 sum (using no elements).target
.num <= current value
, then add dp[current value - num]
to dp[current value]
.dp[target]
.public class CombinationSumIV {
public int combinationSum4(int[] nums, int target) {
// DP array to hold the number of combinations to reach each value up to target
int[] dp = new int[target + 1];
dp[0] = 1; // Base case: there's one way to reach 0, which is using no elements
// Fill the dp array
for (int current = 1; current <= target; current++) {
for (int num : nums) {
if (current >= num) {
dp[current] += dp[current - num];
}
}
}
return dp[target];
}
public static void main(String[] args) {
CombinationSumIV solution = new CombinationSumIV();
int[] nums1 = {1, 2, 3};
int target1 = 4;
System.out.println(solution.combinationSum4(nums1, target1)); // Output: 7
int[] nums2 = {9};
int target2 = 3;
System.out.println(solution.combinationSum4(nums2, target2)); // Output: 0
}
}
n
is the length of the nums
array, and target
is the target value. We iterate through each value up to the target for each number in nums
.target + 1
to store our results.This solution should be efficient and effective for solving the problem within typical constraint limits.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?