简单介绍递归算法以及应用场景

递归就是程序本身调用本身( recursion)算法

通常来讲,递归须要有边界条件递归前进段递归返回段。当边界条件不知足时,递归前进;当边界条件知足时,递归返回。 spa

 

1.趣味问题——年龄。3d

有5我的坐在一块儿,问第五我的多少岁?他说比第4我的大2岁。问第4我的岁数,他说比第3我的大2岁。问第三我的,又说比第2人大两岁。问第2我的,说比第一我的大两岁。最后问第一我的,他说是10岁。请问第五我的多大?用递归算法实现。code

 

 

能够用循环解释这道题orm

        static int GetAge(int num)
        {
            int age = 10;
            while (num>1)
            {
                age += 2;

                num -= 1;
            }
            return age;
        }

换成递归blog

static int GetAge(int num)
{
   if (num==1)
        return 10;
  return GetAge(num-1)+2; }

 

若是换成尾递归递归

        static int GetAge(int num,int acc)
        {
            if (num == 1)
                return acc;
            return GetAge(num-1,acc+2);
        }

3.应用场景内存

删除指定路径下的文件夹里内容以及子文件夹以及子文件夹内容string

        static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                //判断路径是否存在
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    //去除文件夹的只读属性
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0)
                    {
                        DeleteFolder(d1.FullName);////递归删除子文件夹
                    }
                    Directory.Delete(d);
                }
            }
        }

 

4.结io

通常树状结构的均可以使用递归查询,好比 查询地区,树状的菜单等等,递归比普通的算法耗内存,谨慎使用。还有一种叫做“尾递归”就是把上一个方法的返回值看成参数传给下一个方法,不用像递归再向上返回。

相关文章
相关标签/搜索