关于以下来自leetcode的动态编程解决方案中有关scala语法的问题

问题描述 投票:0回答:1

摘自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吗?

scala lazy-evaluation
1个回答
1
投票

...说numSq是可变函数正确吗?

© www.soinside.com 2019 - 2024. All rights reserved.