zoukankan      html  css  js  c++  java
  • 递归函数

    编程语言中,函数Func(Type a,……)直接或间接调用函数本身,则该函数称为递归函数。

    例:输入 5 1 2 3

           输出 11

    不使用递归的方法,使用if......else...

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    #include <stdlib.h>
    //Complete the following function.

    int find_nth_term(int n, int a, int b, int c) {  
     char s[20]={0,1,2,3};
     int sum = 0;
          if(n==1)
          {
             sum=s[1];  
          }
            else if(n==2)
            {
              sum=s[2]; 
            }
                else if(n==3)
                {
                 sum=s[3]; 
                }
                  else if(n==4)
                    {
                     sum=s[1]+s[2]+s[3]; 
                    }
                    else if(n>4)
                    {
                        s[4]=a+b+c;
                        for(int i=4;i<n;i++)
                        {
                           sum = s[n-1]+s[n-2]+s[n-3];
                        }        
                       
                    }
        return sum;              
    }

    int main() {
        int n, a, b, c;
      
        scanf("%d %d %d %d", &n, &a, &b, &c);
        int ans = find_nth_term(n, a, b, c);
     
        printf("%d", ans); 
        return 0;
    }
     
    使用递归

    int find_nth_term(int n, int a, int b, int c) {

        if(n == 1)
        return a;
        else if (n == 2)
        return b;
        else if (n == 3)
        return c;

        return find_nth_term(n-1,a,b,c)+find_nth_term(n-2,a,b,c)+find_nth_term(n-3,a,b,c);
      }

    int main()
    {
      int n, a, b, c;

      scanf("%d %d %d %d", &n, &a, &b, &c);
      int ans = find_nth_term(n, a, b, c);

      printf("%d", ans);
      return 0;

    }

     
  • 相关阅读:
    卫星时间同步装置的安装及售后
    windowsU盘重装系统:操作流程
    vue安装正确流程
    win10以太网未识别的网络
    [UnityShader]unity中2D Sprite显示阴影和接受阴影
    [UnityShader]说厌了的遮挡显示
    [Unity]利用Mesh绘制简单的可被遮挡,可以探测的攻击指示器
    ConcurrentHashMap源码解读
    Vector底层原理
    LinkedList集合底层原理
  • 原文地址:https://www.cnblogs.com/hoganhuang/p/14133843.html
Copyright © 2011-2022 走看看