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.
Example
Solution 1: dynamic programming
Consideration
- For a stair i, the steps to it ways[i] = taking one step to it: ways[i-1] + taking two steps to it: ways[i-2].
Time complexity: O(n). space complexity: O(n)
class Solution {
public int climbStairs(int n) {
int[] ways = new int[n];
for(int i = 0; i < n; i++) {
if(i == 0)
ways[i] = 1;
else if(i == 1)
ways[i] = 2;
else
ways[i] = ways[i-1] + ways[i-2];
}
return ways[n-1];
}
}
Solution 2: brute force, has time limitation problem
Consideration
- We take every combinations of taking either 1 or 2 steps. That is, climbStairs(i,n)=(i+1,n)+climbStairs(i+2,n)
Time complexity : O(2^n). Size of recursion tree will be 2^n. Space complexity: O(n). The depth of the recursion tree can go up to n.
class Solution {
public int climbStairs(int n) {
return climb_stairs(0, n);
}
private int climb_stairs(int i, int n) {
if(i > n)
return 0;
if(i == n)
return 1;
return climb_stairs(i+1, n)+climb_stairs(i+2, n);
}
}
Solution 3: recursion with memoization
Consideration
- We use an array named memo to remember the recursion result.
==Time complexity: O(n). Size of recursion tree can go up to n. Space complexity: O(n). ==
class Solution {
public int climbStairs(int n) {
int memo[] = new int[n];
return climb_stairs(0, n, memo);
}
private int climb_stairs(int i, int n, int[] memo) {
if(i > n)
return 0;
if(i == n)
return 1;
if(memo[i] > 0)
return memo[i];
memo[i] = climb_stairs(i+1, n, memo)+climb_stairs(i+2, n, memo);
return memo[i];
}
Solution 4: Fibonacci Number
Consideration
- In dynamic programming approach, we have used dp array where dp[i]=dp[i-1]+dp[i-2]. dp[i] only relates to i-th fibonacci number.
- Fib(n)=Fib(n−1)+Fib(n−2)
Time complexity : O(n). Single loop up to n is required to calculate n-th fibonacci number. Space complexity : O(1)O(1). Constant space is used.
class Solution {
public int climbStairs(int n) {
if(n == 1)
return 1;
int first = 1;
int second = 2;
for(int i = 3; i <= n; i++) {
int third = first+second;
first = second;
second = third;
}
return second;
}
}
Solution 5: Fibonacci Formula
Consideration
- Fibonacci Formula:
Time complexity : O(log(n)). pow method takes log(n) time. Space complexity : O(1). Constant space is used.
class Solution {
public int climbStairs(int n) {
double sqrt5 = Math.sqrt(5);
double fibn = Math.pow((1+sqrt5)/2, n+1) - Math.pow((1-sqrt5)/2,n+1);
return (int)(fibn/sqrt5);
}
}
Reference