简介

简单来说, 尾递归和使用while循环是差不多的, 编译器会对尾递归函数进行简单的处理,使其性能和while差不多

参考链接

https://www.136.la/tech/show-53755.html
https://blog.csdn.net/cnsword/article/details/3849683

code

class Solution {
public:
    int Fibonacci(int n) {
        return f(n, 0, 1);
    }
    int f(int n, int f1, int f2){
        if(n == 0) {
            return f1;
        }else{
            return f(n-1, f2, f1+f2);
        }
    }
};

性能相差很多倍.

class Solution {
public:
    int Fibonacci(int n) {
        return f(n);
    }
    int f(int n){
        if(n <= 0) {
            return 0;
        }else if(n==1){
            return 1;
        }
        return f(n-1)+f(n-2);
    }
};
posted on 2021-09-11 14:34  HDU李少帅  阅读(37)  评论(0编辑  收藏  举报