递归的例子们

阶乘

class Program
    {
        static int factorical(int n) {
            if (n == 0 || n == 1)
            {
                return 1;
            }
            else
            {
                return n*factorical(n - 1);
            }
        }
        static void Main(string[] args)
        {
            
            Console.WriteLine(factorical(5));
            Console.ReadKey();
        }
    }

斐波那契数列

   static int Fibonacci(int n) {
            if (n == 1||n==2)
            {
                return 1;
            }
            else
            {
                return Fibonacci(n - 1) + Fibonacci(n - 2);
            }
        }
        static void Main(string[] args)
        {
            
            Console.WriteLine(Fibonacci(5));
            Console.ReadKey();
        }

回文

     static bool Palindrome(string s) {
            if (s.Length == 1 || s.Length == 0)
            {
                return true;
            }
            else
            {
                if (s.Substring(0, 1) == s.Substring(s.Length - 1, 1))
                {
                    return Palindrome(s.Substring(1, s.Length - 2));
                    
                }else
                {
                    return false;
                }
               
            }

        }
        static void Main(string[] args)
        {
            
            Console.WriteLine(Palindrome("level"));
            Console.ReadKey();
        }

斐波那契提高版

        static int FibonacciImprove(int a,int b,int n)
        {
            if (n == 3)
            {
                return a+b;
            }
            else
            {
                return FibonacciImprove(b, a + b, n - 1);
            }
        }
        static void Main(string[] args)
        {

            Console.WriteLine(FibonacciImprove(1,1,5));
            Console.ReadKey();
        }

你可能感兴趣的:(递归的例子们)