Using Recursion in C#

前端 未结 10 665
我寻月下人不归
我寻月下人不归 2020-12-14 20:19

Are there any general rules when using recursion on how to avoid stackoverflows?

10条回答
  •  死守一世寂寞
    2020-12-14 20:53

    It really depends on what recursive algorithm you're using. If it's simple recursion, you can do something like this:

    public int CalculateSomethingRecursively(int someNumber)
    {
        return doSomethingRecursively(someNumber, 0);
    }
    
    private int doSomethingRecursively(int someNumber, int level)
    {
        if (level >= MAX_LEVEL || !shouldKeepCalculating(someNumber))
            return someNumber;
        return doSomethingRecursively(someNumber, level + 1);
    }
    

    It's worth noting that this approach is really only useful where the level of recursion can be defined as a logical limit. In the case that this cannot occur (such as a divide and conquer algorithm), you will have to decide how you want to balance simplicity versus performance versus resource limitations. In these cases, you may have to switch between methods once you hit an arbritrary pre-defined limit. An effective means of doing this that I have used in the quicksort algorithm is to do it as a ratio of the total size of the list. In this case, the logical limit is a result of when conditions are no longer optimal.

提交回复
热议问题