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. 完全平方数 #59

Open
Geekhyt opened this issue May 17, 2021 · 0 comments
Open

279. 完全平方数 #59

Geekhyt opened this issue May 17, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented May 17, 2021

原题链接

状态定义

dp[i]: 和为 i 的完全平方数的最少数量

状态转移方程

dp[i] = Math.min(dp[i], i - j * j + 1)

dp[i] 可以由 dp[i - j * j] + 1 推出,取二者中较小者。

初始化

dp[0] = 0

const numSquares = function(n) {
    const dp = new Array(n + 1).fill(0)
    for (let i = 1; i <= n; i++) {
        dp[i] = i
        for (let j = 1; i - j * j >=0; j++) {
            dp[i] = Math.min(dp[i], dp[i - j * j] + 1)            
        }
    }
    return dp[n]
}
  • 时间复杂度:O(n * sqrt(n)),sqrt 为平方根
  • 空间复杂度:O(n)
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant