Questions¶
Difficulty: Easy
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?
Coding¶
python¶
# -*- coding: utf-8 -*-
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 1:
return 1
elif n == 2:
return 2
else:
i, arr = 2, [1,2]
while n > i:
arr.append(arr[i-1]+arr[i-2])
i += 1
return arr[n-1]
Java¶
public class Solution {
public int climbStairs(int n) {
if (n <= 1) {
return 1;
} else if (n == 2) {
return 2;
} else {
int[] array = new int[n + 1];
array[1] = 1;
array[2] = 2;
for (int i = 3; i <= n; i++) {
array[i] = array[i - 1] + array[i - 2];
}
return array[n];
}
}
}