代码拉取完成,页面将自动刷新
package algorithm
import (
llq "github.com/emirpasic/gods/queues/linkedlistqueue"
"github.com/emirpasic/gods/sets/hashset"
)
// Problem Definition: https://leetcode.cn/problems/perfect-squares/
func numSquares1(n int) int {
dp := make([]int, n+1)
for i := 1; i <= n; i++ {
dp[i] = i
for j := 1; j*j <= i; j++ {
dp[i] = min(dp[i], dp[i-j*j]+1)
}
}
return dp[n]
}
func numSquares2(n int) int {
que := llq.New()
visited := hashset.New()
que.Enqueue(0)
visited.Add(0)
level := 0
for !que.Empty() {
ll := que.Size()
level++
for i := 0; i < ll; i++ {
digit, _ := que.Dequeue()
for j := 1; j*j <= n; j++ {
nodeValue := digit.(int) + j*j
if nodeValue == n {
return level
}
if nodeValue > n {
break
}
if !visited.Contains(nodeValue) {
que.Enqueue(nodeValue)
visited.Add(nodeValue)
}
}
}
}
return level
}
func min(a, b int) int {
if a <= b {
return a
}
return b
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。