279. Perfect Squares

来源:互联网 发布:php自动跳转页面 编辑:程序博客网 时间:2024/06/05 17:09

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.


dp的方法很好理解,自己使劲应该可以解决  

dp的解决方法就是从最小的开始向大的方向做遍历,这个递推关系很容易理解,dp[i]=min(dp[i],dp[i-j*j]) j*j要遍历一遍不一定是哪个j 

dp的方法如果dp[i]是记录的数量  很多时候都会比较一个+1/-1   与原值的大小   是否存在会用一个boolean来做


这个题一个比较重要的地方是 在比较的时候设了一个temp值,因为dp在被初始化之后全都是0 不能正确的比较最小值



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


0 0
原创粉丝点击