據(jù)說凡是可以循環(huán)的步驟谤民,都可以遞歸表示出來慎框。
遞歸的關(guān)鍵有二點:
1.0 遞歸公式,即遞推式徒像。
2.0 遞歸出口黍特。
遞歸求數(shù)組的和
package day20180407;
public class Sumarry {
public static void main(String[] args) {
int[] arry= {1,2,3,4,5};
System.out.println("the sum of the arry="+sum(arry,arry.length-1));
}
static int sum(int[] arry,int n)
{
if(n==0)
{
return arry[0];
}
else
{
return sum(arry,n-1)+arry[n];
}
}
}
結(jié)果是
the sum of the arry=15
求數(shù)組的最大數(shù)
package day20180407;
public class Maxarry {
static int count=0;
public static void main(String[] args) {
int[] arry= {1,2,3,4,5,88,-85,1};
System.out.println("the max of the arry="+max(arry,arry.length-1));
System.out.println("count function="+count);
}
static int max(int[] arry,int n)
{
count++;
if(n==0)
{
return arry[0];
}
else
{
if(max(arry,n-1)>arry[n])
return max(arry,n-1);
else
return arry[n];
}
}
}
結(jié)果是:
the max of the arry=88
count function=27
可以看成這個函數(shù),遞歸了20多次锯蛀,你能理解其過程嘛灭衷,反正計算機可以。 我感覺遞歸就像一種哲學(xué)旁涤。