编程题:有n步台阶,一次只能上1步或2步,共有多少种走法?
- 递归
- 循环迭代
递归
/**
* 递归
* @author 17717
*
*/
public class Step2 {
public static void main(String[] args) {
long start=System.currentTimeMillis();
System.out.println(step(40));
long end=System.currentTimeMillis();
System.out.println(end-start+"ms");
}
public static int step(int n) {
if(n<1) {
throw new IllegalArgumentException(n+"不能小于1");
}
if(n==1||n==2) {
return n;
}
return step(n-2)+step(n-1);
}
}
迭代
/**
* 迭代
* @author 17717
*
*/
public class Step1 {
public static void main(String[] args) {
long start=System.currentTimeMillis();
System.out.println(step(30000));
long end=System.currentTimeMillis();
System.out.println(end-start+"ms");
}
public static int step(int n) {
if(n<1) {
throw new IllegalArgumentException(n+"不能小于1");
}
if(n==1||n==2) {
return n;
}
int one=1;
int two=2;
int sum=0;
for(int i=3;i<=n;i++) {
sum=one+two;
one=two;
two=sum;
}
return sum;
}
总结:
• 方法调用自身称为递归,利用变量的原值推出新值称为迭代。
• 递归
• 优点:大问题转化为小问题,可以减少代码量,同时代码精简,可读性好;
• 缺点:递归调用浪费了空间,而且递归太深容易造成堆栈的溢出。
• 迭代
• 优点:代码运行效率好,因为时间只因循环次数增加而增加,而且没有额外的空间开销;
缺点:代码不如递归简洁,可读性好