青蛙跳台阶

青蛙跳台阶

题目:

青蛙一次可以跳1个台阶,也可以跳两个台阶,青蛙跳到第n个台阶有多少种跳法?

题解:

本来不会做,看了下题解,原来反向思考下就又是斐波那契数列问题,而且看到还可以不用递归的方法解。如果青蛙在n个台阶上,那么青蛙可能是n-1个台阶上跳上来的,也可能是n-2个台阶上跳上来的,所以跳到第n个台阶的跳法就是n-1个台阶的跳法加n-2个台阶的跳法之和

import java.util.*;
public class FrogTest {
    public static void main(String [] args)
    {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        System.out.println(jumpMethod(n));
    }
    public static int jumpMethod(int n)
    {
        int a = 1;
        int b = 1;
        for (int i=1; i<n; i++)
        {
            a = a +b;  //a是跳法
            b = a -b;  //b变成了原来的a
        }
        return a;
    }

}

变态跳台阶

题目描述

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

题解:

跳1阶的话,是1种跳法;
跳2阶的话,是2种跳法;
跳3阶的话,是4种跳法;
跳4阶的话,是8种跳法;所以跳n阶的话,是2n-1种跳法。

public class Solution {
    public int JumpFloorII(int target) {
        if (target == 0 || target == 1)
            return 1;
        return power(2, target-1);
    }
    public static int power(int n, int m){
        int a = 1;
        for (int i = 0; i < m; i++){
            a *= n;
        }
        return a;
    }

}

题解:

跳0阶的话,是1种跳法;
跳1阶的话,是1种跳法;
跳2阶的话,是2种跳法;(1+1)
跳3阶的话,是4种跳法;(1+1+2)
跳4阶的话,是8种跳法;(1+1+2+4)
所以跳n阶的话,是 (f(0)+f(1)+f(2)+f(3)+…+f(n-1))种跳法。

public class Solution {
    public int JumpFloorII(int target) {
        if (target == 0)
            return 1;
        int sum = 0;
        int one = 1;
        for (int i = 0; i < target; i++){
            sum += one;  
            one = sum;  
        }
        return sum;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值