Overview
Given an array of distinct positive integers candidates and a target integer target, return the number of possible combinations that add up to target.
Each number in candidates may be used an unlimited number of times. Two combinations are different if the sequence of numbers differs (order matters).
Constraints
1 <= candidates.length <= 2001 <= candidates[i] <= 1000- All elements of
candidatesare distinct. 1 <= target <= 1000
Examples
combinationSum([1, 2, 3], 4); // => 7 // The combinations are: // (1,1,1,1), (1,1,2), (1,2,1), (1,3), // (2,1,1), (2,2), (3,1)
combinationSum([9], 3); // => 0 (no way to reach 3 with only 9s) combinationSum([2, 3], 5); // => 3 (2+3, 3+2, 2+2+... no, just: 2+3, 3+2, 2+2 won't work... => 2+3, 3+2 = 2 ... wait) // Actually: (2,3), (3,2) = 2... let me recalc // Actually for target 5 with [2,3]: 2+3=5, 3+2=5 => 2
Solution
Reveal solution
function combinationSum(candidates, target) {
const dp = new Array(target + 1).fill(0);
dp[0] = 1;
for (let i = 1; i <= target; i++) {
for (const c of candidates) {
if (c <= i) dp[i] += dp[i - c];
}
}
return dp[target];
}This is a bottom-up DP where dp[i] counts the number of ordered combinations summing to i. For each amount, we try adding each candidate.
Resources
Combinations for Target Sum
Overview
Given an array of distinct positive integers candidates and a target integer target, return the number of possible combinations that add up to target.
Each number in candidates may be used an unlimited number of times. Two combinations are different if the sequence of numbers differs (order matters).
Constraints
1 <= candidates.length <= 2001 <= candidates[i] <= 1000- All elements of
candidatesare distinct. 1 <= target <= 1000
Examples
combinationSum([1, 2, 3], 4); // => 7 // The combinations are: // (1,1,1,1), (1,1,2), (1,2,1), (1,3), // (2,1,1), (2,2), (3,1)
combinationSum([9], 3); // => 0 (no way to reach 3 with only 9s) combinationSum([2, 3], 5); // => 3 (2+3, 3+2, 2+2+... no, just: 2+3, 3+2, 2+2 won't work... => 2+3, 3+2 = 2 ... wait) // Actually: (2,3), (3,2) = 2... let me recalc // Actually for target 5 with [2,3]: 2+3=5, 3+2=5 => 2
Solution
Reveal solution
function combinationSum(candidates, target) {
const dp = new Array(target + 1).fill(0);
dp[0] = 1;
for (let i = 1; i <= target; i++) {
for (const c of candidates) {
if (c <= i) dp[i] += dp[i - c];
}
}
return dp[target];
}This is a bottom-up DP where dp[i] counts the number of ordered combinations summing to i. For each amount, we try adding each candidate.