青蛙跳台阶2

问题描述: 一只青蛙一次可以跳上1级台阶,也可以跳上2级······它也可以一次跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。

思路: 第一步跳到第i级,剩下的有f(n-i)种跳法,参考青蛙跳台阶1,故f(n) = f( n - 1) + … + f(n - n),其中f(0) = 0,f(1) = 1,f(2) = 2,又f( n - 1) = f(n - 1 - 1 ) + ··· + f(n - 1 - (n - 1 )),所以f(n) = 2f( n - 1)。即
f ( 0 ) = 0 f ( 1 ) = 1 f ( 2 ) = 2 f ( n ) = f ( n − 1 ) + . . . . . . + f ( n − n ) = 2 f ( n − 1 ) f(0)=0\\f(1)=1\\f(2)=2\\f(n)=f(n-1)+......+f(n-n)=2f(n - 1) f(0)=0f(1)=1f(2)=2f(n)=f(n1)+......+f(nn)=2f(n1)

代码:

package hgy.java.arithmetic;

import org.junit.Test;

public class JumpFloorII {
	//根据思路代码实现
	public int jumpFloor(int target) {
		if (target <= 2)
			return target;
		else
			return 2 * jumpFloor(target - 1);
	}

	// 根据上述代码优化
	public int jumpFloor1(int target) {
		return target > 0 ? 1 << (target - 1) : 0;
	}

	// 模拟动作使用迭代的方法
	public int jumpFloor2(int target) {
		if (target <= 2)
			return target;
		int[] ways = new int[target + 1];
		ways[1] = 1;
		ways[2] = 2;
		for (int i = 3; i <= target; i++) {
			for (int j = 1; j < i; j++)//两步以上跳到终点跳法种数
				ways[i] = ways[i] + ways[j];
			ways[i]++;// 加一步直接跳到终点
		}
		return ways[target];
	}

	@Test
	public void test() {
		System.out.println(jumpFloor(6));
		System.out.println(jumpFloor1(6));
		System.out.println(jumpFloor2(6));
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值