Description
leetcode 70
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.
Java DP solution; Time O(n) Space O(n)
Induction could be visualized as picture below (n=3 example),
n=3 example
Iterating i from 3 to n. For every i, it could be from reached from two ways – one step from position “i-1”, or two steps jump from position “i-2”.
Look at code below, and think about it.
class Solution {
public int climbStairs(int n) {
/**
* Java Dynamic Programming solution
*/
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];
}
}
Runtime: 0ms
Python fabonacci number solution Time O(n), O(1)
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
:algorithm: fibonacci number
"""
if n==1:
return 1
if n==2:
return 2
ret = 0
fib_i_minus_2 = 1
fib_i_minus_1 = 2
for i in xrange(3, n+1):
ret = fib_i_minus_2 + fib_i_minus_1
fib_i_minus_2 = fib_i_minus_1
fib_i_minus_1 = ret
return ret
Runtime: 40ms