279. Perfect Squares

Description

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.

Solution

DP, time O(n * sqrt(n)), space O(n)

本来以为会有什么dark magic,随便写了个DP就过啦竟然。

class Solution {
    public int numSquares(int n) {
        int[] count = new int[n + 1];
        count[0] = 0;
        
        for (int i = 1; i <= n; ++i) {
            count[i] = i;   // made up with 1
            
            for (int j = (int) Math.sqrt(i); j > 0; --j) {
                count[i] = Math.min(count[i], 1 + count[i - j * j]);
            }
        }
        
        return count[n];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,908评论 0 10
  • Given a positive integer n, find the least number of perf...
    Jeanz阅读 304评论 0 0
  • Given a positive integer n, find the least number of perf...
    matrxyz阅读 221评论 0 0
  • MediumGiven a positive integer n, find the least number o...
    greatseniorsde阅读 223评论 0 0
  • 一部经典的影片,鄙人之见,且笑笑看看吧。 如果陪伴安妮的不是乔而是甲(乙,丙,丁都可以只要那人不是乔)那么安妮会爱...
    拇指上的小小人阅读 342评论 0 0

友情链接更多精彩内容