Thursday, April 20, 2017

[LintCode] 513 Perfect Squares 解题报告

Description
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.



Example
Given n = 12, return 3 because 12 = 4 + 4 + 4
Given n = 13, return 2 because 13 = 4 + 9



思路
f[i]表示能够组成i的最小的perfect square个数。
当check到i的时候,我们往前看,看每一个能够再加一个perfect square数组成i的最小的perfect square的数字。



Code
public class Solution {
    /**
     * @param n a positive integer
     * @return an integer
     */
    public int numSquares(int n) {
        // Write your code here
        
        int[] f = new int[n + 1];
        
        for (int i = 1; i <= n; i++) {
            f[i] = i;
            for (int j = 2; j * j <= i; j++) {
                f[i] = Math.min(f[i - j * j] + 1, f[i]);
            }
        }
        
        return f[n];
    }
}