您的位置:首页 > 大数据 > 人工智能

[勇者闯LeetCode] 70. Climbing Stairs

2017-03-26 15:36 369 查看

[勇者闯LeetCode] 70. Climbing Stairs

Description

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?

Note: Given n will be a positive integer.

Information

Tags: Dynamic Programming

Difficulty: Easy

Solution

实质上是Fibonacci Number:

Fib(n)=Fib(n−1)+Fib(n−2),Fib(1)=1,Fib(2)=2,

即爬到n阶的方法数等于爬到n-1阶的方法数和爬到n-2阶的方法数之和,爬到1阶的方法数是1,爬到2阶的方法数是2。

class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
prev, cur = 0, 1
for i in range(n):
prev, cur = cur, cur + prev
return cur
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  algorithm leetcode