摘自here的代码段:
object Solution {
def numSquares(n: Int): Int = {
def memoize[I, O](f: I => O): I => O = new scala.collection.mutable.HashMap[I, O]() {
override def apply(key: I): O = getOrElseUpdate(key, f(key))
}
lazy val numSq: Int => Int = memoize {
case 0 => 0
case x => Range(math.sqrt(x).toInt, 1, -1).foldLeft(x)((a , b) => math.min(numSq(x - b * b) + 1, a))
}
numSq(n)
}
}
由于numSq
使用可变的HashMap,所以说numSq
是可变的函数正确吗?
[通常,在dp中使用自顶向下方法时,通常会在大型输入上导致堆栈溢出-但在这里,即使对于一些较大的输入,它似乎也能正常工作。是因为在lazy val
定义中使用了numSq
吗?
...说
numSq
是可变函数正确吗?