File tree Expand file tree Collapse file tree 1 file changed +26
-0
lines changed
24 - Dynamic Programming Problems/13 - Perfect Squares Expand file tree Collapse file tree 1 file changed +26
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments