Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

279. 完全平方数 #72

Open
webVueBlog opened this issue Sep 5, 2022 · 0 comments
Open

279. 完全平方数 #72

webVueBlog opened this issue Sep 5, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

279. 完全平方数

Description

Difficulty: 中等

Related Topics: 广度优先搜索, 数学, 动态规划

给你一个整数 n ,返回 和为 n 的完全平方数的最少数量

完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,14916 都是完全平方数,而 311 不是。

示例 1:

输入:n = 12
输出:3 
解释:12 = 4 + 4 + 4

示例 2:

输入:n = 13
输出:2
解释:13 = 4 + 9

提示:

  • 1 <= n <= 104

Solution

Language: JavaScript

/**
 * @param {number} n
 * @return {number}
 */
/**
 * @param {number} n
 * @return {number}
 */
// dp[i] 表示i的完全平方和的最少数量,dp[i-j*j] + 1 表示减去一个完全平方数j的完全平方之后的数量加1就等于dp[i]
// 只要在dp[i], dp[i-j*j] + 1 中寻找一个较少的就是最后 dp[i] 的值
var numSquares = function(n) {
    const dp = new Array(n + 1).fill(Infinity);
    dp[0] = 0;

    for(let i = 1; i**2 <= n; i++) {
        for(let j = i**2; j <= n; j++) {
            dp[j] = Math.min(dp[j - i**2] + 1, dp[j]);
        }
    }

    return dp[n];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant