Skip to content

Commit 265078d

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 22f13c1 commit 265078d

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
};

0 commit comments

Comments
 (0)