|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Recursive function to calculate the number of combinations with memoization |
| 4 | + int solve(vector<int>& nums, int target, vector<int>& dp) { |
| 5 | + // Base case: If the target becomes negative, no valid combination is possible |
| 6 | + if(target < 0) return 0; |
| 7 | + |
| 8 | + // Base case: If the target becomes zero, one valid combination is found |
| 9 | + if(target == 0) return 1; |
| 10 | + |
| 11 | + // If the result for the current target has already been calculated, return it |
| 12 | + if(dp[target] != -1) return dp[target]; |
| 13 | + |
| 14 | + // Initialize a variable to store the number of valid combinations for the current target |
| 15 | + int ans = 0; |
| 16 | + |
| 17 | + // Iterate through each number in the array |
| 18 | + for(int i = 0; i < nums.size(); i++) { |
| 19 | + // Recursively calculate combinations for the reduced target |
| 20 | + ans += solve(nums, target - nums[i], dp); |
| 21 | + } |
| 22 | + |
| 23 | + // Store the calculated result in the memoization table |
| 24 | + dp[target] = ans; |
| 25 | + |
| 26 | + // Return the result for the current target |
| 27 | + return dp[target]; |
| 28 | + } |
| 29 | + |
| 30 | + // Main function to calculate the number of combinations for a given target |
| 31 | + int combinationSum4(vector<int>& nums, int target) { |
| 32 | + // Initialize a memoization table with -1 (uncomputed state) |
| 33 | + vector<int> dp(target + 1, -1); |
| 34 | + |
| 35 | + // Call the recursive function to solve the problem with memoization |
| 36 | + return solve(nums, target, dp); |
| 37 | + } |
| 38 | +}; |
0 commit comments