第一題bfs + 圖 , 效率很低
pesudo code :
make a queue
make a visited map
push [n,0] into queue // [n,0] means [currentNumRemain , stepsCount]
while queue is not empty
pop pairs
currnumRemain = pairs[0]
steps = pairs[1]
iterate from 0 until i*i<=currentNum
if currNum-i*i==0
return step+1
if i*i already visited // 因為已經有其他路徑先到達了
pass
else
push [currNum-i*i,step+1] into queue
func numSquares(n int) int {
q:=[][]int{}
vm:=make(map[int]int)
q=append(q,[]int{n,0})
for len(q)!=0 {
//pop pairs
pairs:=q[0]
q=q[1:]
currNumRemain:=pairs[0]
steps:=pairs[1]
for i:=0;i*i<=currNumRemain;i++ {
if currNumRemain-i*i==0 {
return steps+1
}
if _,ok:=vm[i*i];ok {
continue
} else {
q=append(q,[]int{currNumRemain-i*i,steps+1})
}
}
}
return 0
}