青蛙跳台阶,可以跳1阶,也可以跳2阶,N阶台阶有多少种跳的方式,算法题

	/**
	 * @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;  
	}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值