/**
* @param args
*/
public static void main(String[] args) {
test t = new test();
t.ottest();
}
三种方法各有优劣利弊,
ottest()内调用
public class test {
int allStep = 2; //总台阶
int allMethods= 0; //总方法
int times = 0; //计算次数
public void ottest(){
if(allStep > 0){
ottest(allStep);
//ottest2(allStep);
//ottest3(allStep);
}
System.out.println("allMethods:"+allMethods+",times:"+times);
}
//case1: when nowStep = 0 , allMethods++ ,速度较慢 可扩展性高
private void ottest(int nowStep){
times++;
if(nowStep <= 0){
if(nowStep == 0){
allMethods++;
}
return;
}
ottest(nowStep-1);
ottest(nowStep-2);
//ottest(nowStep-3);//可以跳3步?
}
//case2: fn-1 + fn-2 ,递归方法 速度中 可扩展性中
private int ottest2(int nowStep){
times++;
if(nowStep == 1 || nowStep == 2){
allMethods = nowStep;
return nowStep;
}
allMethods = ottest2(nowStep-1) + ottest2(nowStep-2);
return allMethods;
}
//case3: fn-1 + fn-2 ,数学方法,速度快 可扩展性差
public int ottest3(int target) {
int result = 0;
int first = 1;
int second = 2;
if(target==1 || target== 2) {
result = target;
}else {
for(int i = 3; i <= target; i++) {
result = first + second;
first = second;
second = result;
}
}
return result;
}
}