G9 - Perfect Square

May 25, 2017

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

Solution :
use Dynamic programming to find the solution for smaller numbers, and use that to find solution for bigger numbers

                
public class Solution {
    public int numSquares(int n) {
        if(n < 4)
            return n;

        int[] dp = new int[n+1];
        dp[0] = 0;
        dp[1] = 1;
        dp[2] = 2;
        dp[3] = 3;
        for(int i=4; i<=n; i++){
            dp[i] = i;
            for(int j=1; j<=i; j++){
                int temp = j*j;
                if(temp > i)
                    break;
                else{
                    dp[i] = Math.min(dp[i], dp[i-temp]+1);
                }
            }
        }
        return dp[n];
    }
}