LintCode:完美平方

LintCode:完美平方

public class Solution {
    /**
     * @param n a positive integer
     * @return an integer
     */
    public int numSquares(int n) {
        // Write your code here
        int[] dp = new int[n+1];
        for(int i=0; i<=n; i++){
            dp[i] = Integer.MAX_VALUE;
        }
        for(int i=0; i*i<=n; i++){
            dp[i*i] = 1;
        }
        for(int i=0; i<=n; i++){
            for(int j=0; i+j*j<=n; j++){
                //System.out.println(i+j*j);
                dp[i+j*j] = Math.min(dp[i]+1, dp[i+j*j]);
            }
        }
        return dp[n];
    }
}
posted @ 2017-05-31 20:13  天涯海角路  阅读(128)  评论(0)    收藏  举报