File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed
24 - Dynamic Programming Problems/12 - Combination Sum IV Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Recursive function to calculate the number of combinations
4+ int solve (vector<int >& nums, int target) {
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+ // Initialize a variable to store the number of valid combinations
12+ int ans = 0 ;
13+
14+ // Iterate through each number in the array
15+ for (int i = 0 ; i < nums.size (); i++) {
16+ // Recursively reduce the target by the current number and add the result
17+ ans += solve (nums, target - nums[i]);
18+ }
19+
20+ // Return the total number of valid combinations for the current target
21+ return ans;
22+ }
23+
24+ // Main function to calculate the number of combinations for a given target
25+ int combinationSum4 (vector<int >& nums, int target) {
26+ // Call the recursive function to solve the problem
27+ return solve (nums, target);
28+ }
29+ };
You can’t perform that action at this time.
0 commit comments