*[Lintcode]Perfect Square

来源:互联网 发布:sql执行顺序 编辑:程序博客网 时间:2024/05/19 02:16

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


分析:先是递归,超时。

public class Solution {    /**     * @param n a positive integer     * @return an integer     */    public int numSquares(int n) {        int[] min = new int[1];        min[0] = Integer.MAX_VALUE;        helper(n, 0, min);        return min[0];    }        void helper(int n, int res, int[] min) {        if(n == 0) {            min[0] = Math.min(res, min[0]);            return;        }        if(n == 1) {            min[0] = Math.min(res + 1, min[0]);            return;        }        for(int i = 1; i <= n; i++) {            if(i * i <= n) {                helper(n - i * i, res + 1, min);            }        }    }}

考虑使用一维DP。

public class Solution {    /**     * @param n a positive integer     * @return an integer     */    public int numSquares(int n) {        int[] min = new int[n + 1];        min[0] = 0;        for(int i = 1; i <= n; i++) min[i] = Integer.MAX_VALUE;        for(int i = 0; i < n; i++) {            for(int j = 1; i + j * j <= n; j++) {//j start from 1 instead of i + 1                min[i + j * j] = Math.min(min[i + j * j], min[i] + 1);            }        }        return min[n];    }    }


0 0
原创粉丝点击