279. Perfect Squares**

来源:互联网 发布:大型公司网络组建 编辑:程序博客网 时间:2024/05/24 01:51

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.

My code:

public class Solution {    public int numSquares(int n) {        if(n<=0) return 0;        int result[]=new int[n+1];        Arrays.fill(result,Integer.MAX_VALUE);        result[0]=0;        result[1]=1;        for(int i=2; i<n+1;i++){            for (int j=(int) Math.floor(Math.sqrt(i));j>0;j--){                if (i-Math.pow(j,2)>=0){                    result[i]=Math.min(result[i],result[(int)(i-Math.pow(j,2))]+1);                }            }        }        return result[n];    }}



0 0