前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode-70-Climbing Stairs

LeetCode-70-Climbing Stairs

作者头像
欠扁的小篮子
发布2018-04-11 11:23:39
5460
发布2018-04-11 11:23:39
举报
文章被收录于专栏:技术碎碎念

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个台阶的话,一共有几种方法爬到顶端。

思路:

  n<=1,此时只有一种。

  n>1时,对于每一个台阶i,要到达台阶,最后一步都有两种方法,从i-1迈一步,或从i-2迈两步。

  也就是说到达台阶i的方法数=达台阶i-1的方法数+达台阶i-2的方法数。所以该问题是个DP问题。

d(0) = 1

d(1) = 1

d(2) = d(2-1) + d(2-2)

d(3) = d(3-1) + d(3-2)

……

好吧,状态转移方程其实就是Fibonacci数列。

代码实现给出两种方案吧:

python代码如下:

代码语言:javascript
复制
 1 class Solution(object):
 2     def climbStairs(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         if n<=1:
 8             return 1
 9         res = []
10         res.append(1)
11         res.append(1)
12         for i in range(2,n+1):
13             res.append(res[-1]+res[-2])
14         return res[-1]

Java代码如下:

代码语言:javascript
复制
 1 public class Solution {
 2     public int climbStairs(int n) {
 3         if (n<=1)
 4             return 1;
 5 
 6         int oneStep=1,twoStep = 1,res = 0;
 7 
 8         for (int i = 2; i <= n; i++) {
 9             res = oneStep + twoStep;
10             twoStep = oneStep;
11             oneStep = res;
12         }
13         
14         return res;
15     }
16 }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016-06-24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档