题目:
一只青蛙一次可以跳上1级台阶,也可以跳上2级台阶。求该青蛙跳上一个n级台阶总共有多少种跳法。
思路:
我是利用枚举的方式,试了n=6之前的情况
发现这个跟斐波那契数列一样,所以就利用了递归的思想。
代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11public class Solution { public int JumpFloor(int target) { if(target==1){ return 1; } if(target==2){ return 2; } return (JumpFloor(target-1)+JumpFloor(target-2)); } }
下面是看了别人的解法之后,利用非递归的思想实现的。
代码:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19public class Solution { public int JumpFloor(int target) { if(target==1){ return 1; } if(target==2){ return 2; } int n1=1; int n2=2; int total=0; for(int i=3;i<=target;i++){ total=n1+n2; n1=n2; n2=total; } return total; } }
最后
以上就是单身大山最近收集整理的关于牛客网 跳台阶的全部内容,更多相关牛客网内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复