[LeetCode] 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.For example, given n = 12, return 3 because 12 = 4 + 4 + 4; give

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.

Subscribe to see which companies asked this question

解题思路

动态规划法。初始化时令dp[i * i] = 1,状态转移方程为dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);

实现代码

C++:

// Runtime: 544 ms
class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + 1, 0x7fffffff);
        for (int i = 0; i * i <= n; i++)
        {
            dp[i * i] = 1;
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; i + j * j <= n; j++)
            {
                dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);
            }
        }

        return dp[n];
    }
};

Java:

// Runtime: 69 ms
public class Solution {
    public int numSquares(int n) {
        int dp[] = new int[n + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        for (int i = 1; i * i <= n; i++) {
            dp[i * i] = 1;
        }
        for (int i = 1; i <= n; i++) {
            for (int j = 1; i + j * j <= n; j++) {
                dp[i + j * j] = Math.min(dp[i] + 1, dp[i + j * j]);
            }
        }

        return dp[n];
    }
}
目录
相关文章
LeetCode 367. Valid Perfect Square
给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。
78 0
LeetCode 367. Valid Perfect Square
LeetCode 279. Perfect Squares
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
52 0
LeetCode 279. Perfect Squares
Leetcode-Easy 977. Squares of a Sorted Array
Leetcode-Easy 977. Squares of a Sorted Array
85 0
|
C++
[LeetCode] Perfect Squares
Well, after seeing the similar problems, you may have known how to solve this problem. Yeah, just to construct larger numbers from smaller numbers by adding perfect squares to them.
714 0
|
16天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
16天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
17天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值