【leetcode】Climbing Stairs

题目简述:

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阶的种数要不然是从第n-1阶走一步上去,要不然是从第n-2阶走两步上去。写成数学式子就是:\(a[n]=a[n-1]+a[n-2]\)

class Solution:
    # @param n, an integer
    # @return an integer
    def climbStairs(self, n):
        if n == 1:
            return 1
        if n == 2:
            return 2
        a = [None] * n
        a[0] = 1
        a[1] = 2
        for i in range(2,n):
            a[i] = a[i-1] + a[i-2]
        return a[n-1]
posted @ 2015-01-17 16:00  mrbean  阅读(273)  评论(0编辑  收藏  举报