How to avoid StackOverflowError for a recursive function

后端 未结 6 1533
无人共我
无人共我 2021-01-01 18:19

I\'m writing a function that will call itself up to about 5000 times. Ofcourse, I get a StackOverflowError. Is there any way that I can rewrite this code in a f

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 18:49

    In most cases recursion is used in a wrong way. You shouldn't get a stack over flow exception. Your method has no return type/value. How do you ensure your initial Block b is valid?

    If you are using recursion, answer yourself the following question:

    • what is my recursion anchor (when do i stop with recursion)
    • what is my recursion step (how do I reduce my number of calculations)

    Example:

    • n! => n*n-1!

    my recursion anchor is n == 2 (result is 2), so I can calculate all results beginnging from this anchor.

    my recursion step is n-1 (so each step I get closer to the solution (and in this fact to my recursion anchor))

提交回复
热议问题