Skip to content

Commit 0f526b0

Browse files
authored
Create 01 - Recursive Approach (caused TLE).cpp
1 parent 7898977 commit 0f526b0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the minimum number of perfect squares
4+
int solve(int n){
5+
// Base case: If n is 0, no numbers are needed to sum to 0.
6+
if(n == 0) return 0;
7+
8+
// Initialize ans with a large number. We'll try to minimize this value.
9+
int ans = INT_MAX;
10+
11+
// Loop through all possible perfect squares less than or equal to n
12+
for(int i = 1; i * i <= n; i++) {
13+
// Recursively calculate the minimum number of perfect squares for the remaining value
14+
// After subtracting the current perfect square (i * i) from n
15+
ans = min(ans, solve(n - i*i) + 1);
16+
}
17+
18+
// Return the minimum number of perfect squares for the given n
19+
return ans;
20+
}
21+
22+
// Main function to call the solve function and return the result for the input n
23+
int numSquares(int n) {
24+
return solve(n);
25+
}
26+
};

0 commit comments

Comments
 (0)