算法笔记: 力扣#70 爬楼梯

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
class :
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return n
first, second = 1, 2
for _ in range(3, n+1):
first, second = second, first + second
return second

Java 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
class {
public int climbStairs(int n) {
if(n < 3){ return n; }
int first = 1;
int second = 2;
for(int i = 3; i <= n; i++){
int temp = first + second;
first = second;
second = temp;
}
return second;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


70. Climbing Stairs
70. 爬楼梯
(English version) Algorithm Notes: Leetcode#70 Climbing Stairs