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 target
.
The problem differs from the combination sum problem because the order of the integers in the combination matters.
nums = [1,2,3], target = 4
7
nums = [9], target = 3
0
nums
array?
nums
are positive and distinct.nums
be empty or target
be zero?
nums
and target
will be a positive integer.We will use Dynamic Programming (DP) to solve this problem. The idea is to build an array dp
where dp[i]
represents the number of combinations that add up to the target i
.
target + 1
with zeros: std::vector<int> dp(target + 1, 0)
.dp[0] = 1
because there’s one way to reach the target 0, which is by using no elements.target
.nums
.dp[current target - num]
.dp[target]
which will give us the number of combinations to form the target.n
is the length of nums
, and we iterate through the target
for each number in nums
.target + 1
.#include <iostream>
#include <vector>
int combinationSum4(std::vector<int>& nums, int target) {
std::vector<int> dp(target + 1, 0);
dp[0] = 1; // There is one way to reach target 0, by using no elements.
for (int i = 1; i <= target; ++i) {
for (const int& num : nums) {
if (i - num >= 0) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
int main() {
std::vector<int> nums1 = {1, 2, 3};
int target1 = 4;
std::cout << "Number of combinations for target " << target1 << " is: " << combinationSum4(nums1, target1) << std::endl; // Output: 7
std::vector<int> nums2 = {9};
int target2 = 3;
std::cout << "Number of combinations for target " << target2 << " is: " << combinationSum4(nums2, target2) << std::endl; // Output: 0
return 0;
}
The provided code snippet initializes the DP array, updates it based on possible sums for each target value, and finally prints the result for provided cases.
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?