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