跳台阶

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

思路:类似于斐波那契序列,跳上第n(n>3)级台阶,之前最后一步跳1级或2级。

步骤:

1 如果台阶级数n<=2,则返回n。

2 根据f(n)=f(n-1)+f(n-2),计算结果并返回。

Java代码:

public class Solution {
    public int JumpFloor(int target) {
        if (target == 1 || target == 2) {
            return target;
        }
        
        // a是f(n-1),b是f(n-2)
        int a = 2, b = 1, c = 0;
        for (int i = 3; i <= target; i++) {
            c = a + b;
            // b顶替a
            b = a;
		    // a顶替c 
            a = c;
        }
        
        return c;
    }
}

 

posted on 2025-11-29 15:11  王景迁  阅读(4)  评论(0)    收藏  举报

导航