Convert normal recursion to tail recursion

后端 未结 6 766
悲哀的现实
悲哀的现实 2020-12-13 07:30

I was wondering if there is some general method to convert a \"normal\" recursion with foo(...) + foo(...) as the last call to a tail-recursion.

For exa

6条回答
  •  既然无缘
    2020-12-13 07:51

    The accumulator approach

      def pascal(c: Int, r: Int): Int = {
    
        def pascalAcc(acc:Int, leftover: List[(Int, Int)]):Int = {
          if (leftover.isEmpty) acc
          else {
            val (c1, r1) = leftover.head
            // Edge.
            if (c1 == 0 || c1 == r1) pascalAcc(acc + 1, leftover.tail)
            // Safe checks.
            else if (c1 < 0 || r1 < 0 || c1 > r1) pascalAcc(acc, leftover.tail)
            // Add 2 other points to accumulator.
            else pascalAcc(acc, (c1 , r1 - 1) :: ((c1 - 1, r1 - 1) :: leftover.tail ))
          }
        }
    
        pascalAcc(0, List ((c,r) ))
      }
    

    It does not overflow the stack but as on big row and column but Aaron mentioned it's not fast.

提交回复
热议问题