LC 70. Climbing Stairs

Sarthak Sehgal · April 11, 2020

This is one of the most standard DP problems. It can be easily seen that the person can come to a step i either from step i-1 or step i-2. Define dp[i] as number of ways to end up at i-th stair. Clearly, dp[i] = dp[i-1] + dp[i-2].

int climbStairs(int n) {
		int dp[n+1] = {0};

		if (n==0)
				return 1;
		if (n>=1)
				dp[1] = 1;
		if (n>=2)
				dp[2] = 2;

		for (int i=3; i<n+1; i++) {
				dp[i] = dp[i-1] + dp[i-2];
		}

		return dp[n];
}

Time complexity: O(n)
Space complexity: O(n)

We can further reduce the time complexity by observing that we only require dp[i-1] and dp[i-2] to determine dp[i]. Also observe that this is a classical Fibonacci series.

public int climbStairs(int n) {
    // base cases
    if(n <= 0) return 0;
    if(n == 1) return 1;
    if(n == 2) return 2;

    int one_step_before = 2;
    int two_steps_before = 1;
    int all_ways = 0;

    for(int i=2; i<n; i++){
    	all_ways = one_step_before + two_steps_before;
    	two_steps_before = one_step_before;
      one_step_before = all_ways;
    }
    return all_ways;
}

Twitter, Facebook