Advertisement
1988coder

279. Perfect Squares

Nov 29th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.64 KB | None | 0 0
  1. /*
  2. Dynamic Programming
  3. Time Complexity: O(sqrt(1) + sqrt(2) + sqrt(3) + ... + sqrt(n))
  4. Space Complexity: O(n)
  5. */
  6. class Solution {
  7.     public int numSquares(int n) {
  8.         if (n < 1) {
  9.             return 0;
  10.         }
  11.         if (n == 1) {
  12.             return 1;
  13.         }
  14.        
  15.         int[] dp = new int[n+1];
  16.         dp[1] = 1;
  17.        
  18.         for (int i = 2; i <= n; i++) {
  19.             int minCount = Integer.MAX_VALUE;
  20.             for (int j = 1; j * j <= i; j++) {
  21.                 minCount = Math.min(minCount, dp[i - j*j] + 1);
  22.             }
  23.             dp[i] = minCount;
  24.         }
  25.        
  26.         return dp[n];
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement