Advertisement
Guest User

numSquares C++

a guest
Oct 14th, 2019
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. class Solution {
  6. public:
  7.     int numSquares(int n) {
  8.         int nsqrt = (int)sqrt(n);
  9.         vector<int> perfectSquares = {0};
  10.         for(int i = 1; i < nsqrt+1; i++){
  11.             perfectSquares.push_back(i*i);
  12.         }
  13.         int nps = perfectSquares.size();
  14.         int m[n+1][nps];
  15.         for(int i = 0; i <= n; i++){
  16.             for(int j = 0; j < nps; j++)
  17.                 m[i][j] = 0;
  18.         }
  19.  
  20.         for(int i = 0; i <= n; i++){
  21.             m[i][0] = INT_MAX - 1;
  22.         }
  23.         for(int i = 1; i <= n; i++){
  24.             for(int j = 1; j < nps; j++){
  25.                 int curPerfectSquare = perfectSquares[j];
  26.                 if(curPerfectSquare > i){
  27.                     m[i][j] = m[i][j-1];
  28.                 }else{
  29.                     m[i][j] = min(m[i][j-1],1+m[i-curPerfectSquare][j]);
  30.                 }
  31.             }
  32.         }
  33.         return m[n][nps-1];
  34.     }
  35. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement