递归算法常见习题代码(控制台程序)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Test
{
    class Program
    {
        //递归计算中的两种模式
        //1:通过递归来获取最后一项的值(与前面的每个递归结果都没有关联)
        //2:通过递归来获取整个递归过程中的总和

        //注意:递归算法中的循环结束点判断条件,递归算法中的递归完成之后,其中的变量的作用域判断。
        static void Main(string[] args)
        {
            Console.WriteLine("1:题目要求:1-2+3-4+5-6+7-8+9=");
            Console.WriteLine("结果为:{0}", getRes(9, 0));
            Console.WriteLine("2:计算数字的阶乘");
            Console.WriteLine("{0}!结果为:{1}", 5, getJC(5));
            Console.WriteLine("3:不定长度的数字转换为字符串");
            Console.WriteLine("结果为:{0}", getStr(812345, ""));
            Console.WriteLine("4: 编写计算斐波那契(Fibonacci)");
            for (int i = 1; i <= 15; i++)
            {
                Console.Write(getFibonacci(i) + ",");
            }
            Console.Write('\n');
            Console.WriteLine("5:求1+2+3+4+5+....+n的值");
            Console.WriteLine("结果为:{0}",getSum(10));
            Console.Read();
        }
        //栈(递归算法[作用域],四则运算)
        //递归中,栈中的数据的作用域的范围理解了
        //1题
        public static int getRes(int count, int res)
        {
            if (count < 2)
                return res + 1;
            else
            {
                if (count % 2 == 0)
                {
                    res = res - count;
                }
                else
                {
                    res = res + count;
                }
                return getRes(count - 1, res);
            }
        }
        //2:递归计算阶乘
        public static int getJC(int count)
        {
            if (count < 2)
                return 1;
            else
                return count * getJC(count - 1);
        }

        //3:把整数转换为相应的字符串
        public static string getStr(int val, string res)
        {
            if (val / 10 == 0)
            {
                return (val % 10) + res;
            }
            else
            {
                res = (val % 10) + res;
                return getStr(val / 10, res);
            }
        }
        //4:编写计算斐波那契
        public static int getFibonacci(int count)
        {
            if (count <= 2)
                return count;
            else
            {
                return getFibonacci(count - 2) + getFibonacci(count - 1);
            }
        }

        public static int getSum(int count)
        {
            if (count <= 1)
                return count;
            else
            {
                return count + getSum(count - 1);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/snowhumen/p/2777057.html