
Sponsored
Sponsored
This approach involves creating a recursive solution while storing intermediate results in a memoization array to avoid redundant calculations. Define a recursive function that calculates the number of ways to reach the target from the given list, and store the results of subproblems.
Time Complexity: O(target * numsSize).
Space Complexity: O(target).
1var combinationSum4 = function(nums, target) {
2 const memo = Array(target + 1).fill(-1);
3 memo[0] = 1;
4
5 const dfs = (target) => {
6 if (target < 0) return 0;
7 if (memo[target] !== -1) return memo[target];
8
9 let count = 0;
10 for (const num of nums) {
11 count += dfs(target - num);
12 }
13
14 memo[target] = count;
15 return count;
16 };
17
18 return dfs(target);
19};
20
21console.log(combinationSum4([1, 2, 3], 4));The JavaScript solution makes use of memoization to handle previously solved subproblems, employing a recursive method to find multiple combinations to form the target sum.
In this method, an iterative bottom-up approach is used. A DP array is created where each index represents the number of ways to sum to that index using numbers from nums. We incrementally build solutions from smaller subproblems to solve for larger targets.
Time Complexity: O(target * numsSize).
Space Complexity: O(target).
1using System;
public class Solution {
public int CombinationSum4(int[] nums, int target) {
int[] dp = new int[target + 1];
dp[0] = 1;
for (int i = 1; i <= target; i++) {
foreach (int num in nums) {
if (i - num >= 0) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
public static void Main(string[] args) {
var sol = new Solution();
Console.WriteLine(sol.CombinationSum4(new[] { 1, 2, 3 }, 4));
}
}This C# solution uses a DP array approach to calculate the number of combinations iteratively by determining how many ways each sub-target can be formed from the elements in nums.