目录
迭代能解决的问题递归也能解决,递归能够解决的问题,迭代不一定,递归是分治法的一种实现方式
先来看下一个比较的简单的求1-100和的递归方法
package test1;
public class diguiTest {
public static void main(String[] args) {
System.out.println(diguiTest.f(100));
}
public static int f(int n) {
if(n==1) {
return 1;
}
return f(n-1)+n;
}
}
递归的使用的条件就是:
一定要有结束条件,这个比较关键
2,斐波那契数列,求前20项
1 1 2 3 5 8 13 21 34 55 .............规律就是前两项这和等于第三项
求这个数列的前20项,第一种解法,这种解法的时间复杂度是n*Math.pow(n,2)
package test1;
public class diguiTest {
public static void main(String[] args) {
for(int i=1;i<=20;i++) {
System.out.print(diguiTest.febo(i)+" ");
}
}
public static int febo(int n) {
if(n==1||n==2) {//递归的结束条件
return 1;
}
return febo(n-1)+febo(n-2);
}
}
第二种解法时间复杂度就是n
package test1;
public class diguiTest {
public static void main(String[] args) {
diguiTest.iteratorTest(20);
}
public static int febo(int n) {
if(n==1||n==2) {//递归的结束条件
return 1;
}
return febo(n-1)+febo(n-2);
}
public static void iteratorTest(int n) {
int a=1;
int b=1;
int c;
System.out.print(a+","+b+" ");
int count=2;
while(count<=n) {
c=a+b;
System.out.print(c+" ");
a=b;
b=c;
count++;
}
}
}