leetcode 70. Climbing Stairs
2016-03-14 21:11
483 查看
题目内容
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
题目分析
我们假设,最后一步完成爬台阶。那么就有两种爬法出现,n-1和n-2两种情况。而完成n步的情况就为,F(n)种,可以推出F(n)=F(n-1)+F(n-2)种。
所以不难发现,递推关系,
F(n)=F(n-1)+F(n-2)
是斐波那契数列。。。。如果发现不了你就记住!!!这个式子是斐波那契数列.
所以解题有两种方式常用的方式,递归,和迭代。
递归一般因为占用空间太大而被抛弃。在leetcode上跑了一下,大概能计算到n=44.
迭代的话,是个正向的过程,直接从n=1开始加,加到n,时间复杂度为 O(n)。
递归
迭代
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
题目分析
我们假设,最后一步完成爬台阶。那么就有两种爬法出现,n-1和n-2两种情况。而完成n步的情况就为,F(n)种,可以推出F(n)=F(n-1)+F(n-2)种。
所以不难发现,递推关系,
F(n)=F(n-1)+F(n-2)
是斐波那契数列。。。。如果发现不了你就记住!!!这个式子是斐波那契数列.
所以解题有两种方式常用的方式,递归,和迭代。
递归一般因为占用空间太大而被抛弃。在leetcode上跑了一下,大概能计算到n=44.
迭代的话,是个正向的过程,直接从n=1开始加,加到n,时间复杂度为 O(n)。
递归
public class Solution { public int climbStairs(int n) { int ans=re(n); return ans; } public int re(int n) { if(n<1) return n; int ans=re(n-1)+re(n-2); return ans; } }
迭代
public class Solution { public int climbStairs(int n) { int one=0; int two=1; int sum=0; for(int i=0;i<n;i++) { sum=one+two; one =two; two=sum; } return sum; } }
相关文章推荐
- HDU.1022 Train Problem I【栈的简单应用】(3.14)
- HDU4300 Clairewd’s message
- 【leetcode】第11题:Container问题
- 关灯游戏AI扩展
- git RPC failed;result=18
- Socket bind failed: [730048] ͨ³£ÿ¸öÌÓ×ֵØַ(ЭÒé/ÍøÂçµØַ/¶˿Ú)ֻÔÊÐíʹÓ
- EventMailer使用方法
- ERROR: Upgrade faifailed bin/mysqlcheck: Got error: 1045: Access denied for user 'root'@'localhost'
- 用TextPaint来绘制文字
- [BZOJ 4320]ShangHai2006 Homework
- 游戏人工智能开发之6种决策方法
- lightoj 1021 - Painful Bases 状压DP
- System and device programming——R&W with semaphore
- An error was encountered while running(Domain=LaunchSerivcesError, Code=0)
- 发现大量的TIME_WAIT解决办法
- la 4394 string painter 区间dp
- 查看AIX文件系统分布所在的物理磁盘
- Flask-mail 邮件带中文名称的附件
- [AIR] Screen 的应用
- 简述raid0、raid1、raid5的区别