递归算法学习

递归就是程序自己调用自己( recursion)

一般来说,递归需要有边界条件递归前进段递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。 

 

1.趣味问题——年龄。

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

可以用循环解释这道题

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

                num -= 1;
            }
            return age;
        }
复制代码

换成递归

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.应用场景

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

复制代码
        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.结

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




汉诺塔问题

如图,汉诺塔问题是指有三根杆子A,B,C。C杆上有若干碟子,把所有碟子从A杆上移到C杆上,每次只能移动一个碟子,大的碟子不能叠在小的碟子上面。求最少要移动多少次?

当n=1时:

Move  1  from  A  to  C
当n=2时:
Move  1  from  A  to  B
Move  2  from  A  to  C
Move  1  from  B  to  C

当n=3时:
Move  1  from  A  to  C
Move  2  from  A  to  B
Move  1  from  C  to  B
Move  3  from  A  to  C
Move  1  from  B  to  A
Move  2  from  B  to  C
Move  1  from  A  to  C

源代码

  1. static StringBuffer str = new StringBuffer();  
  2.     /** 
  3.      * //汉诺塔问题 
  4.      * @param n 盘子的个数 
  5.      * @param x 将要移动盘子柱子 
  6.      * @param y 要借用的柱子 
  7.      * @param z 要移动到的柱子 
  8.      * @return 
  9.      */  
  10.     public static String hanio(int n, Object x, Object y, Object z) {  
  11.         //String str ="";  
  12.         if(1 == n)   
  13.             str.append(move(x, n, z) + "\n");  
  14.         else {  
  15.             hanio(n-1, x, z, y);  
  16.             str.append(move(x, n, z) + "\n") ;  
  17.             hanio(n-1, y, x, z);  
  18.         }  
  19.         return str.toString();  
  20.     }  
  21.     private static String move(Object x, int n, Object y) {  
  22.         //System.out.println("Move  " + n + "  from  " + x + "  to  " + y);  
  23.         return "Move  " + n + "  from  " + x + "  to  " + y;  
  24.     }  
  25.       

fibonacci数列

斐波纳契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……在数学上,斐波纳契数列以如下被以递归的方法定义:F0=0,F1=1,Fn=F(n-1)+F(n-2)(n>=2,n∈N*)

源代码

  1. /** 
  2.      * fibonacci数列 
  3.      * @param n 
  4.      * @return 
  5.      */  
  6.     public static long fibonacci(int n) {  
  7.         if((0 == n) || (1 == n)) {  
  8.             return n;  
  9.         }else {  
  10.             return fibonacci(n-1) + fibonacci(n-2);  
  11.         }  
  12.     }  

1加到n累加

用递归实现从1加到n,即1+2+3+4+...+n。

源代码

  1. /** 
  2.      * 累加,从1加到n,即1+2+3+4+...+n 
  3.      * @param n 要累加到的数值 
  4.      * @return 累加的结果 
  5.      */  
  6.     public static long total(int n) {  
  7.         if(1 == n) {  
  8.             return n;  
  9.         }else {  
  10.             return total(n-1) + n;  
  11.         }  
  12.     }  

从1到n累积

用递归实现,从1到n累积,即1*2*3*...*n

源代码

  1. /** 
  2.      * 从1到n的累积,即1*2*3*...*n 
  3.      * @param n 要累乖到的数值 
  4.      * @return 
  5.      */  
  6.     public static long accumulate(int n) {   
  7.         if(1 == n) {  
  8.             return n;  
  9.         }else {  
  10.             return accumulate(n-1) * n;  
  11.         }  
  12.     }  

求数组中的最大值

用递归算法求数组中的最大值。

源代码

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 用递归算法求数组中的最大值 
  3.      * @param a 数组 
  4.      * @param low 数组下标 
  5.      * @param heigh 数组上标 
  6.      * @return 
  7.      */  
  8.     public static int Max(int[] a, int low, int heigh) {  
  9.         int max;  
  10.         if(low > heigh-2) {  
  11.             if(a[low] > a[heigh]) max = a[low];  
  12.             else max = a[heigh];  
  13.         }else {  
  14.             int mid = (low + heigh)/2;  
  15.             int max1 = Max(a, low, mid);  
  16.             int max2 = Max(a, mid+1, heigh);  
  17.             max = max1>max2 ? max1 : max2;  
  18.         }  
  19.         return max;  
  20.     }  


数字塔问题

用递归算法求解数字塔问题。
n=1时
1
n=2时
1      
2      2     
 
n=3时
1      
2      2      
3      3      3  
 
n=4时
1      
2      2      
3      3      3      
4      4      4      4
    

源代码

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 用递归算法求解数字塔问题 
  3.      * @param n 数字塔的行数 
  4.      * @return 数字塔的字符串 
  5.      */  
  6.     public static String tourData(int n) {  
  7.         String str = new String();  
  8.         if(1 == n) {  
  9.             str = rowData(n) + "\n";  
  10.             return str;  
  11.         }  
  12.         else {  
  13.             str = tourData(n-1) + rowData(n) + "\n";  
  14.         }  
  15.         return str;  
  16.     }  
  17.     private static String rowData(int n) {  
  18.         String str = new String();  
  19.         for(int i=0; i<n; i++) {  
  20.             str = str+ n + "      ";  
  21.         }  
  22.         return str;  
  23.     }  

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值