欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

斐波那契数列算法,青蛙跳台阶

程序员文章站 2024-03-20 10:50:52
...

青蛙跳台阶,一次可跳一阶或两阶,跳到第n阶时有几种跳法

package com.art.arithmetic.count;

public class FrogJumpOrder {

	public static void main(String[] args) {
		FrogJumpOrder frogJumpOrder = new FrogJumpOrder();
		System.out.println(frogJumpOrder.getMethodNum(4));
		System.out.println(frogJumpOrder.getMethodNum(5));
		System.out.println(frogJumpOrder.getMethodNum(6));
		System.out.println(frogJumpOrder.getMethodNum(7));
		System.out.println(frogJumpOrder.getMethodNum(8));
	}
	
	/**
	 * 能跳到第n阶的方式有从n-1阶跳或从n-2阶跳,那么就需要获取跳到n-1和n-2时各有多少种方法,依次类推
	 * @return
	 */
	public long getMethodNum(long n) {
		if (n < 1) {
			return 0;
		}
		if (n == 1) {
			return 1;
		}
		if (n == 2) {
			return 2;
		}
		return getMethodNum(n-1) + getMethodNum(n-2);
	}

}