
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).
1using System;
2
3public class Solution {
4 public int CombinationSum4(int[] nums, int target) {
5 var memo = new int[target + 1];
6 Array.Fill(memo, -1);
7 memo[0] = 1;
8 return Dfs(nums, target, memo);
9 }
10
11 private int Dfs(int[] nums, int target, int[] memo) {
12 if (target < 0) return 0;
13 if (memo[target] != -1) return memo[target];
14
15 int count = 0;
16 foreach (var num in nums) {
17 count += Dfs(nums, target - num, memo);
18 }
19
20 memo[target] = count;
21 return count;
22 }
23
24 public static void Main(string[] args) {
25 var sol = new Solution();
26 Console.WriteLine(sol.CombinationSum4(new[] { 1, 2, 3 }, 4));
27 }
28}The C# implementation uses recursion with memoization via a helper method 'Dfs' to calculate the combination sums iteratively in a top-down manner.
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).
1#
This C implementation uses a DP array where each element at index i stores the number of ways to form the sum i, iterating through each number in nums to update the array.