Concise Java Solution


  • 0
    2
    public int numSquares(int n)
    {
    	int[] count=new int[n+1];
    	for(int i=1;i<=n;i++)
    	{
    		double maxD=Math.sqrt(i);
    		int maxI=(int)maxD;
    		if(maxI==maxD)
    		{
    			count[i]=1;
    			continue;
    		}
    		for(int j=1;j<=maxI;j++)
    		{
    			count[i]=(count[i]==0)?count[i-j*j]+1:Math.min(count[i], count[i-j*j]+1);
    		}
    	}
    	return count[n];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.