
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#include <vector>
#include <iostream>
class Solution {
public:
int combinationSum4(std::vector<int>& nums, int target) {
std::vector<unsigned int> dp(target + 1, 0);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (const auto& num : nums) {
if (i - num >= 0) {
dp[i] += dp[i - num];
}
}
}
return dp[target];
}
};
int main() {
Solution sol;
std::vector<int> nums = {1, 2, 3};
int target = 4;
std::cout << sol.combinationSum4(nums, target) << std::endl;
return 0;
}In this C++ solution, we use an array dp to store computed values. For each number from 1 to the target, we explore all available nums to determine how many ways the target can be formed.