【java】求该青蛙跳上一个n级的台阶总共有多少种跳法

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
台阶数 跳法
0 0
1 1
2 2
3 3
4 5
5 8
类似斐波那契数列,用递归或迭代比较简单,不过注意开头

package 牛客;

import java.util.Scanner;

public class 跳台阶 {
	public static int JumpFloor(int target) {
       int sum=0;
       int  f1=1;
       int  f2=2;
       if(target==0) {
    	   return 0;
       }
       else if(target==1) {
    	   return 1;
       }
       else if(target==2) {
    	   return 2;
       }
       else {
       for(int i=2;i<target;i++)
       {
    	   sum=f1+f2;
    	   f1=f2;
    	   f2=sum;
       }
       return sum;
       }
    }
	public static void main(String[] args) {
		Scanner s= new Scanner(System.in);
		System.out.println("输入台阶数:");
		int t=s.nextInt();
		System.out.println("共"+(JumpFloor(t))+"种方法");

	}

}

猜你喜欢

转载自blog.csdn.net/qq_43416226/article/details/89878764