《剑指offer》69--跳台阶[C++][Java]

跳台阶_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力https://www.nowcoder.com/practice/8c82a5b80378478f9484d87d1c5f12a4?tpId=13&tags=&title=&difficulty=0&judgeStatus=0&rp=1

 题目描述

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

解题思路

当 n = 1 时,只有一种跳法:

当 n = 2 时,有两种跳法:

跳 n 阶台阶,可以先跳 1 阶台阶,再跳 n-1 阶台阶;或者先跳 2 阶台阶,再跳 n-2 阶台阶。而 n-1 和 n-2 阶台阶的跳法可以看成子问题,该问题的递推公式为:

【C++解法】

class Solution {
public:
    int jumpFloor(int number) {
        int j1 = 1, j2 = 2, jn = number;
        for(int i=3; i<=number; i++) {
            jn = j1+j2;
            j1 = j2;
            j2 = jn;
        }
        return jn;
    }
};

 【Java解法】

public class Solution {
    public int jumpFloor(int target) {
        int f1 = 1, f2 = 2, fn = target;
        for (int i = 3; i <= target; i++) {
            fn = f1 + f2;
            f1 = f2;
            f2 = fn;
        }
        return fn;
    }
}

同类型题目

LeetCode-70. Climbing Stairs [C++][Java]_贫道绝缘子的博客-CSDN博客You are climbing a staircase. It takesnsteps to reach the top. Each time you can either climb1or2steps. In how many distinct ways can you climb to the top?https://blog.csdn.net/qq_15711195/article/details/123342137

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贫道绝缘子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值