File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
24 - Dynamic Programming Problems/13 - Perfect Squares Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Function to calculate the minimum number of perfect squares
4+ int solve (int n){
5+ // Create a DP array of size n+1 initialized with INT_MAX (a large value representing infinity)
6+ // dp[i] will store the minimum number of perfect squares required to sum to i.
7+ vector<int > dp (n+1 , INT_MAX);
8+
9+ // Base case: dp[0] = 0, as no squares are needed to sum to 0.
10+ dp[0 ] = 0 ;
11+
12+ // Iterate over all values of i from 1 to n
13+ for (int i = 1 ; i <= n; i++){
14+ // For each i, check all perfect squares (j * j) that are less than or equal to i
15+ for (int j = 1 ; j * j <= i; j++){
16+ int SQRT = j * j; // Square of j
17+
18+ // If subtracting SQRT from i doesn't make it negative, update dp[i]
19+ // Take the minimum of the current value of dp[i] and dp[i - SQRT] + 1
20+ // (the +1 is because we are using one more square, i.e., SQRT)
21+ dp[i] = min (dp[i], dp[i - SQRT] + 1 );
22+ }
23+ }
24+
25+ // Return the minimum number of perfect squares for the number n
26+ return dp[n];
27+ }
28+
29+ // Main function to return the minimum number of perfect squares for n
30+ int numSquares (int n) {
31+ return solve (n); // Call the solve function to calculate the result
32+ }
33+ };
You can’t perform that action at this time.
0 commit comments