2019年10月18日 星期五

Climbing Stairs


Climbing Stairs

  • Lintcode : 111 / Leetcode : 70
  • Level : Easy

Problem

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?

Example
Example 1:
    Input:  n = 3
    Output: 3

    Explanation:
    1) 1, 1, 1
    2) 1, 2
    3) 2, 1
    total 3.

Example 2:
    Input:  n = 1
    Output: 1

    Explanation:  
    only 1 way.

Concept & Algorithm

Time Complexity & Space Complexity

time : O(n)
space: O(n)

Answer

class Solution {
public:
    int climbStairs(int n) {
        vector<int> dp(n + 1, 0);
        if (n == 0) return 0;
        if (n == 1) return 1;
        dp[0] = 1;
        dp[1] = 1;
        for (int i = 2; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
};
tags: DP

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...