
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).
1class Solution:
2 def combinationSum4(self, nums, target):
3 memo = [-1] * (target + 1)
4 memo[0] = 1
5
6 def dfs(target):
7 if target < 0:
8 return 0
9 if memo[target] != -1:
10 return memo[target]
11
12 count = 0
13 for num in nums:
14 count += dfs(target - num)
15 memo[target] = count
16 return count
17
18 return dfs(target)
19
20sol = Solution()
21print(sol.combinationSum4([1, 2, 3], 4))The Python solution uses a recursive bottom-up approach with memoization to store previously computed results, allowing it to find the valid combinations efficiently.
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.