leetcode Perfect Squares

来源:互联网 发布:变频布林线源码 编辑:程序博客网 时间:2024/06/05 16:18

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.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

经典dp题目,dp题目最重要的是找状态转移方程,https://segmentfault.com/a/1190000003768736讲的非常清楚,这道题是为了找构成整数所需的最小个数的平方数,可以理解为若n=a+b*b,那么n所需的最小平方数个数为a所需的最小平方数个数+1,如果能想到这里这道题基本就解决了,我们只需要找到小于等于n的所有平方数,将他们的初值设为1,然后进行比较即可,代码:

public int numSquares(int n) {    int[] res=new int[n+1];    Arrays.fill(res,Integer.MAX_VALUE);    for(int i=0;i*i<=n;i++){        res[i*i]=1;    }    for(int a=0;a<=n;a++){        for(int b=0;a+b*b<=n;b++){            res[a+b*b]=Math.min(res[a]+1,res[a+b*b]);        }    }    return res[n];}

0 0
原创粉丝点击