7.31递归函数专题总结

· · 个人记录

温馨提醒:未满114514岁的小朋友禁止观看。

今天也是写了一篇水文章。

递归函数:

函数的写法:

返回值类型 函数名称(参数类型 参数名称){
    具体代码…
    return 和返回值类型一样的值;
}

例子:

int f(int n){
    if (n == 1) return n;
    return n+f(n-1);
}

唐人棕节:

B2148 再求 f(x,n):

  1. ❌原因:不会。

  2. ❌代码:

    #include<bits/stdc++.h>
    using namespace std;
    double f(int x,int n){
     if (x == 0) return f(x,n);
     return x/f(x,n-1);
    }
    int main(){
    
     int x,n;
     cin >> x >> n;
     printf("%.02f",f(x,n));
    
     return 0;
    }
    //纯乱写。
  3. 烤差只是点:不是递归还能是什么?

  4. 姐体死路:看图。

  5. ✔️代码:

    #include<bits/stdc++.h>
    using namespace std;
    double f(int n,double x){
     if(n == 1) return x/(1+x);
     return x/(f(n-1,x)+n);
    }
    int main(){
    
     int n;
     double x;
     cin >> x >> n;
     printf("%.02f",f(n,x)); //输出两位浮点数。
    
     return 0;
    }

    U143068 2的幂次方表示:

  6. ❌原因:没写。

  7. ❌代码:没写就肯定木有。

    1. 烤差只是点:不是递归还能是什么?
  8. 姐体死路:看代码。

  9. ✔️代码:

    #include<bits/stdc++.h>
    using namespace std;
    int pow2[20];
    void f(int x){
     for (int i = 15;i >= 0;i--){
         if (pow2[i] <= x){
             if (i == 0){ //判断i是否为0。
                 cout << "2(0)";
             }else if (i == 1){ //判断i是否为1。
                 cout << "2";
             }else { //判断其他情况。
                 cout << "2(";
                 f(i);
                 cout << ")";
             }
             x -= pow2[i];
             if (x > 0){ //判断x还有没有。
                 cout << "+";
             }
         }
     }
    }
    int main(){
    
     int n;
     cin >> n;
     pow2[0] = 1; //2^0=1。
     for (int i = 1;i <= 15;i++){
         pow2[i] = pow2[i-1] *2; // 赋值。
     }
     f(n); //在函数里输出。
    
     return 0;
    }

    U523561 汉诺塔:

  10. ❌原因:骗分。

  11. ❌代码:

    #include<bits/stdc++.h>
    using namespace std;
    int main(){
    
     int n;
     cin >> n;
     if (n == 1) cout << "A -> C";
     if (n == 2) cout << "A -> B" << endl << "A -> C" << endl << "B -> C";
     if (n == 3){
         cout << "A -> C" << endl << "A -> B" << endl << "C -> B" << endl << "A -> C" << endl << "B -> A" << endl << "B -> C" << endl << "A -> C";
     }
    
     return 0;
    }
    1. 烤差只是点:不是递归还能是什么?
  12. 姐体死路:看代码。

  13. ✔️代码:

    #include<bits/stdc++.h>
    using namespace std;
    void f(int n,char st,char mid,char ed){
     if (n == 1){
         cout << st << " -> " << ed << endl;
         return ;
     }
     f(n-1,st,ed,mid);
     f(1,st,mid,ed);
     f(n-1,mid,st,ed);
    }
    int main(){
    
     int n;
     cin >> n;
     f(n,'A','B','C'); //在函数里输出。
    
     return 0;
    }

    洛谷全明星:

  14. AC(代表你✔️)。

  15. WA(代表你这个代码有❌)。

  16. RE(代表你数组小了或者越界了)。

  17. TLE(代表你代码重新写吧,your代码超时了)。

  18. OLE(代表你输出太多了)。

  19. MLE(代表你代码超内存了)。

  20. CE(代表你代码编译错误)。

  21. UKE(我不知道,我没见过)。

    测谎仪:

  22. 这篇文章很水[✔️]。

  23. 老师是帅哥[✔️]。

    好心人留个赞。