Java:青蛙跳台阶问题。

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

1个台阶:1     1种

2个台阶:1+1  2   2种

3个台阶:1+1+1   2+1   1+2    3种

4个台阶:1+1+1+1    1+2+1    2+2    1+1+2     2+1+1    5种

所以第n级台阶的跳法为(n-1)+(n-2)的和。

1、使用递归的方法:

import java.util.Scanner;
public class TestDemo6 {
    public static int jump(int n) {
        int count = 1;
        if(n==1||n==2) {
            return n;
        }
        return jump(n-1)+jump(n-2);
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int floor = scan.nextInt();
        System.out.println(jump(floor));
    }
}

2、迭代方法:

import java.util.Scanner;
public class TestDemo7 {
    public static int jump(int n) {
        if(n==1||n==2) {
            return n;
        }
        int i = 1; int j = 2;int sum = 0;//5
        for (int m = 3;m<=n;m++) {
            sum = i+j;
            i = j;
            j = sum;
    }
        return sum;
    }
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int floor = scan.nextInt();
        System.out.println(jump(floor));
    }
}
发布了82 篇原创文章 · 获赞 0 · 访问量 1177

猜你喜欢

转载自blog.csdn.net/yufy0528/article/details/104850958
今日推荐