leetcode Perfect Squares

题目链接

思想动态规划:
record[i]=Math.min(record[i],record[i-j*j]+record[j*j]);

代码

public class Solution {
    public int numSquares(int n) {
        int record[]=new int [n+1];
        record[0]=0;
        record[1]=1;
        for(int i=2;i<=n;i++)
        {
            for(int j=(int)Math.sqrt(i);j>=1;j--)
            {
                if(j*j==i)
                {
                    record[i]=1;
                    break;
                }
                record[i]=record[i]==0?record[i-j*j]+record[j*j]:Math.min(record[i],record[i-j*j]+record[j*j]);
            }
        }

        return record[n];
    }
}

你可能感兴趣的:(leetcode Perfect Squares)