[LeetCode]279. Perfect Squares

来源:互联网 发布:linux 所在目录 编辑:程序博客网 时间:2024/06/04 17:53

https://leetcode.com/problems/perfect-squares/

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



当前位置所构成和所需要的数的总数的最小值为前序序列之中,与当前位置距离差为平方数的dp的最小值加一。当前位置平方数和所需要的平方数肯定是由某一个平方数加上当前位置与该平方数差的数所需的平方数总数加一组成的。

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


0 0
原创粉丝点击