递归函数

编程语言中,函数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;

}

 
posted @ 2020-12-14 16:11  堕落的黑天使  阅读(184)  评论(0编辑  收藏  举报