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;

    }

     
  • 相关阅读:
    开发技术--Numpy模块
    开发技术-IPython介绍
    开发--Deepin系统安装
    开发--CentOS-7安装及配置
    开发技术--设计模式
    English--音标重难点
    English--音标拼读
    English--辅音
    jQuery火箭图标返回顶部代码
    jQuery火箭图标返回顶部代码
  • 原文地址:https://www.cnblogs.com/hoganhuang/p/14133843.html
Copyright © 2011-2022 走看看