/** * 题目: * 一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。 * 解题思路: * 当n>2时,第一次跳的时候就有两种不同的选择: * 一是第一次只跳1级,此时跳法数目等于剩下的n-1级台阶的跳法数目,即f(n-1) * 二是第一次跳2级,此时跳法数目等于后面剩下的n-2级台阶的跳法数目,即(n-2) * 因此,n级台阶的跳法总数目f(n)=f(n-1)+f(n-2) */ public class P77_FrogJumpFloor { public int FrogJumpFloor(int target) { int result = 0; if (target == 2 || target == 1) { result = target; } int temp1 = 1; int temp2 = 2; for (int i = 3; i <= target; i++) { result = temp1 + temp2; temp1 = temp2; temp2 = result; } return result; } public static void main(String[] args) { int n = 2; P77_FrogJumpFloor test = new P77_FrogJumpFloor(); int result = test.FrogJumpFloor(n); System.out.print(result); } }
剑指offer:青蛙跳台阶问题(java)
最新推荐文章于 2023-02-23 20:35:59 发布