
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).
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.