上台阶(爬楼梯)

来源:https://leetcode.com/problems/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?

Note: Given n will be a positive integer.

Python

class Solution(object):
    def climbStairs(self, n):
        """
        :type n: int
        :rtype: int
        """
        # f(n) = f(n-1) + f(n-2)
        if n == 1: return 1
        if n == 2: return 2
        a, b = 1, 2
        for i in xrange(n-2):
            a, b = b, a+b
        return b

Java

class Solution {
    public int climbStairs(int n) {
        int[] f = new int[n+1];
        f[0] = 0;
        if(n >= 1) f[1] = 1;
        if(n >= 2) f[2] = 2;
        for(int i=3; i<=n; i++) {
            f[i] = f[i-1] + f[i-2];
        }
        return f[n];        
    }
}
posted @ 2017-08-30 21:41  HitAnyKey  阅读(309)  评论(0)    收藏  举报