Fastrail08

Perfect Squares Leetcode 279

Jul 7th, 2025
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.70 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. /*
  4. QUESTION = https://leetcode.com/problems/perfect-squares/
  5.  
  6. */
  7. int getMinSquares(int n, vector<int> &memo){
  8.     //base case
  9.     //if n == 0, min steps needed to reach 0 is 0
  10.     if(n == 0){
  11.         return 0;
  12.     }
  13.     if(memo[n] != -1){
  14.         return memo[n];
  15.     }
  16.     int minSteps = INT_MAX;
  17.     //level = each N
  18.     //options = values upto sqrt(N)
  19.     for(int i = 1; i * i <= n; i++){
  20.         minSteps = min(minSteps, 1 + getMinSquares(n - (i * i), memo));
  21.     }
  22.     return memo[n] = minSteps;
  23. }
  24.  
  25. int main() {
  26.     // your code goes here
  27.     int n;
  28.     cin >> n;
  29.     vector<int> memo(n + 1, -1);
  30.     cout << getMinSquares(n, memo) << '\n';
  31. }
  32.  
Advertisement
Add Comment
Please, Sign In to add comment