1 Star 0 Fork 0

Paulden/Algorithm

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
num_squares.go 955 Bytes
一键复制 编辑 原始数据 按行查看 历史
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
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/guuzaa/algorithm.git
git@gitee.com:guuzaa/algorithm.git
guuzaa
algorithm
Algorithm
main

搜索帮助

23e8dbc6 1850385 7e0993f3 1850385