话不多说先上原题:
以下我将会以四种方法来解题,自行分析递归调用的弊端:
package com.爬楼梯;
/*
* 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
*
* 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
*
* 注意:给定 n 是一个正整数。
*/
public class Solution {
public static void main(String[] args) {
long start1 = System.currentTimeMillis();
System.out.println(palou(40));
long end1 = System.currentTimeMillis();
System.out.println("for循环算时间:"+(end1-start1));
long start2 = System.currentTimeMillis();
System.out.println(palou2(40));
long end2= System.currentTimeMillis();
System.out.println("while循环算时间:"+(end2-start2));
long start3 = System.currentTimeMillis();
System.out.println(palou3(40));
long end3= System.currentTimeMillis();
System.out.println("递归方法(一)时间:"+(end3-start3));
long start4 = System.currentTimeMillis();
System.out.println(climb_Stairs(0, 40));
long end4= System.currentTimeMillis();
System.out.println("递归方法(二)时间:"+(end4-start4));
}
public static int palou(int n){
int result = 0;
int f1 = 1;
int f2 = 2;
if (n == 1||n==2) {
return n;
}
//指针前移
for (int i = 3; i <= n; i++) {
result = f1 + f2;
f1 = f2;
f2 = result;
}
return result;
}
public static int palou2(int n){
if (n == 1||n==2) {
return n;
}
else {
int res = 0;
int i = 1, j = 2;
int k = 3;
while (k <= n) {
res = i + j;
i = j;
j = res;
k++;
}
return res;
}
}
//递归方法自己调用自己(所用时间长)
/**
* 比如要求Y4 = Y3 + Y2 = Y2 + Y1 + Y1 + Y0
*
*不断推进,直到基准情形
*
*/
public static int climb_Stairs(int i, int n) {
if (i > n) {
return 0;
}
if (i == n) {
return 1;
}
return climb_Stairs(i + 1, n) + climb_Stairs(i + 2, n);
}
public static int palou3(int n) {
if (n == 1 || n == 2) {
return n;
}
return palou3(n-1) +palou3(n-2);
}
}
运行结果: