跳台阶(剑指offer)

二级台阶

跳台阶
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)

public class Solution {
    
    
    public int JumpFloor(int target) {
    
    
        if(target<=0){
    
    
            return 0;
        }
        if(target==1){
    
    
            return 1;
        }
        if(target==2){
    
    
            return 2;
        }
        int a=1;
        int b=2;
        int result=0;
        for(int i=2;i<target;i++){
    
    
            result=a+b;
            a=b;
            b=result;
        }
        return result;
    }
}

三级台阶

来源:三级台阶

有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。请实现一个方法,计算小孩有多少种上楼的方式。为了防止溢出,请将结果Mod 1000000007

给定一个正整数int n,请返回一个数,代表上楼的方式数。保证n小于等于100000。
在这里插入图片描述

import java.util.*;

public class GoUpstairs {
    
    
    public int countWays(int n) {
    
    
        long[] pre={
    
    1,2,4};
        if(n<=0){
    
    
            return 0;
        }else if(n<=3){
    
    
            return (int)pre[n-1];
        }else{
    
    
            for(int i=4;i<=n;i++){
    
    
                long tmp=(pre[0]+pre[1]+pre[2])%1000000007;
                pre[0]=pre[1];
                pre[1]=pre[2];
                pre[2]=tmp;
            }
        }
        return (int)pre[2];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_44929652/article/details/107687990