Suppose you are climbing stairs. You need n
steps to get to the top of the building.
Every time you can climb 1
or 2
a step. How many different ways can you get to the top of the building?
class Solution {
public int climbStairs(int n) {
//f(n) = f(n - 1) + f(n -2)
int p = 0, q = 0, r = 1;
for (int i = 1; i <= n; ++i) {
p = q;
q = r;
r = p + q;
}
return r;
}
}
Time complexity: The loop is executed n times, and each time takes a constant time cost, so the asymptotic time complexity is O(n).
Space complexity: Here only constant variables are used as auxiliary space, so the asymptotic space complexity is O(1).