L70 Climbing Stairs

Fibonacci Number && DP

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(different) ways can you climb to the top?

Note: Given n will be a positive integer.

Example:

Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps

Solution

s1: Fibonacci Number

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

  • TC: O(n) Single loop up to n is required to calculate n^th fibonacci number.

  • SC:O(1) Constant space is used.

public int countStep(int n){
    if(n <= 2) return n;
    int prePre = 0;
    int pre = 1;
    int cur = 2;
    
    for(int i = 2 ; i <= n; i++){
        cur = pre + prePre;
        prePre = pre;
        pre = cur;
    }
    return cur;
}

S2: DP

  • Time complexity : O(n)O(n). Single loop upto nn.

  • Space complexity : O(n)O(n). dpdp array of size nn is used.

public class Solution {
    public int climbStairs(int n) {
        if (n == 1) {
            return 1;
        }
        int[] dp = new int[n + 1];
        dp[1] = 1;
        dp[2] = 2;
        for (int i = 3; i <= n; i++) {
            dp[i] = dp[i - 1] + dp[i - 2];
        }
        return dp[n];
    }
}

Last updated

Was this helpful?