JAVA frog jumping off the stairs

JAVA frog jumping off the stairs

problem

Question: When facing a step, a frog can jump up once. When facing two steps, you can choose to jump two at a time or one at a time twice. When facing three steps, you can also jump two at a time or one jump three times... , The frog can jump one step or two steps at a time. Q: How many mid-jump methods are there when there are N steps?

First summarize the rules as follows:

A step: one kind of jumps;
two steps: two kinds of jumps;
three steps: three kinds of jumps;
four steps: five kinds of jumps;
five steps: eight kinds of jumps;
. . . . .
The jumping method of N steps is (N-1) step jumping method + (N-2) step jumping method;

Code:

Through recursion: `

static int frogjump(int n){
    
    
        if(n ==1){
    
    
            return 1;
        }else if(n ==2){
    
    
            return 2;
        }else{
    
    
            return frogjump(n-1)+frogjump(n-2);
        }
    }

Realized by loop:

static int frogjump2(int n ){
    
    
        if(n==1){
    
    
            return 1;
        }else if(n==2){
    
    
            return 2;
        }else{
    
    
            int a = 1;
            int b = 2;
            int tmp = 0;
            for(int i=3;i<=n;i++){
    
    
                tmp = a+b;
                a = b;
                b = tmp;
            }
            return tmp;
        }

Guess you like

Origin blog.csdn.net/weixin_44712669/article/details/110876968