-
-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathcombinationSum4.js
More file actions
32 lines (30 loc) · 773 Bytes
/
combinationSum4.js
File metadata and controls
32 lines (30 loc) · 773 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// TC: O(n * target), SC: O(target)
function combinationSum4(nums, target) {
if (nums.length === 0) return 0;
if (target === 0) return 1;
let dp = new Array(target + 1).fill(0);
dp[0] = 1;
for (let i = 1; i <= target; i++) {
for (let num of nums) {
if (i >= num) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
// Test cases
let testCases = [
{ nums: [1, 2, 4], target: 5 },
{ nums: [7], target: 6 },
{ nums: [], target: 5 }, // Edge: empty nums
{ nums: [1, 2], target: 0 }, // Edge: target zero
{ nums: [3, 4, 5], target: 8 },
];
for (const { nums, target } of testCases) {
console.log(
`Nums: ${JSON.stringify(
nums
)}, Target: ${target} | CombinationSum4: ${combinationSum4(nums, target)}`
);
}