Advertisement
imashutosh51

Perfect squares

Oct 16th, 2022 (edited)
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 KB | None | 0 0
  1. /*
  2. any n can contain the squares of natural numbers eg. 1,4,9,16,25...sqrt(n)*sqrt(n)
  3. so we have to select minimum numbers among the square of natural numbers.
  4. This is similar to Coin denomination problem where value will go from 1 to n and
  5. denominations are 1,4,9,16,suppose we put it in array ie. arr
  6. so,We will be having a 2d dp table in which i=1 to n and j=0 to sizeof(arr)-1;
  7. Logic:Either you select the jth currency or not.
  8. case 1: i==jth denomination so we can achieve that amount in only one step and smaller than that is not possible.
  9. case 2: i< jth denomination so we can't select the current denomination so this amount can be achieved by not selecting this denomination.
  10. case 3: i>jth denomination
  11.   if(j==0): means we have only one denomination ie. 1 so with 1,we need i of 1    to make it equal to i,there is no any other option.
  12.   else : we are having more than one denomination so either select this denomination or don't select.keep one          point in mind,if we select the denomination,then check for i-denomination row but in same column
  13.          because same denomination can be repeated also.
  14. */
  15.  
  16. class Solution {
  17. public:
  18.     int numSquares(int n) {
  19.         vector <int> arr;
  20.         int k=sqrt(n);
  21.         for(int i=1;i<=k;i++){
  22.             arr.push_back(i*i);
  23.         }
  24.         int dp[n+1][arr.size()];
  25.         for(int j=0;j<arr.size();j++) dp[0][j]=0;
  26.         for(int i=1;i<n+1;i++){
  27.             for(int j=0;j<arr.size();j++){
  28.                 if(i==arr[j]) dp[i][j]=1;
  29.                 else if(i>arr[j]){
  30.                     if(j==0) dp[i][j]=i;
  31.                     else dp[i][j]=min(dp[i-arr[j]][j]+1,dp[i][j-1]);
  32.                 }
  33.                 else dp[i][j]=dp[i][j-1];
  34.             }
  35.         }
  36.         return dp[n][arr.size()-1];
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement