Skip to content

Commit 62fa5de

Browse files
authored
Create 02 - Top-Down | DP | Approach.cpp
1 parent 0f526b0 commit 62fa5de

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution {
2+
public:
3+
// Recursive function to calculate the minimum number of perfect squares
4+
// using memoization to avoid redundant calculations
5+
int solve(int n, vector<int> &dp){
6+
// Base case: dp[0] = 0, as 0 can be represented by 0 perfect squares
7+
dp[0] = 0;
8+
9+
// If the result for the current value of n has already been computed, return it
10+
if(dp[n] != -1) return dp[n];
11+
12+
// Initialize ans to the maximum possible value, which is n (since n can be represented
13+
// by the sum of n 1's (1^2), which is the worst case)
14+
int ans = n;
15+
16+
// Try all perfect squares less than or equal to n
17+
for(int i = 1; i * i <= n; i++){
18+
// The current square number
19+
int SQRT = i * i;
20+
21+
// Recursively calculate the minimum squares needed for the remaining value (n - SQRT)
22+
ans = min(ans, solve(n - SQRT, dp) + 1); // Add 1 for the current perfect square used
23+
}
24+
25+
// Store the result for the current value of n to avoid recalculating it
26+
dp[n] = ans;
27+
28+
// Return the minimum number of perfect squares for the current value of n
29+
return dp[n];
30+
}
31+
32+
// Main function to calculate the minimum number of perfect squares for the input n
33+
int numSquares(int n) {
34+
// Create a DP array of size n+1 initialized with -1 (indicating that no value has been computed yet)
35+
vector<int> dp(n+1, -1);
36+
37+
// Call the recursive function with memoization to compute the result
38+
return solve(n, dp);
39+
}
40+
};

0 commit comments

Comments
 (0)