3

#yyds干货盘点# 面试必刷TOP101:跳台阶

 1 year ago
source link: https://blog.51cto.com/u_15488507/5717160
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 面试必刷TOP101:跳台阶

精选 原创

97的风 2022-09-27 17:17:08 博主文章分类:面试题 ©著作权

文章标签 初始化 数据 时间复杂度 文章分类 Java 编程语言 阅读数212

1.简述:

描述

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

数据范围:

要求:时间复杂度: ,空间复杂度: 

示例1
青蛙要跳上两级台阶有两种跳法,分别是:先跳一级,再跳一级或者直接跳两级。因此答案为2
示例2

2.代码实现:

public class Solution {
public int jumpFloor(int target) {
//从0开始,第0项是0,第一项是1
if(target <= 1)
return 1;
int res = 0;
int a = 0;
int b = 1;
//因n=2时也为1,初始化的时候把a=0,b=1
for(int i = 2; i <= target; i++){
//第三项开始是前两项的和,然后保留最新的两项,更新数据相加
res = (a + b);
a = b;
b = res;
}
return res;
}
}
  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK