70 爬楼梯

本文最后更新于:2021年8月17日 下午

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

注意:给定 n 是一个正整数。

示例 1:

1
2
3
4
5
输入: 2
输出: 2
解释: 有两种方法可以爬到楼顶。
1. 1 阶 + 1
2. 2

示例 2:

1
2
3
4
5
6
输入: 3
输出: 3
解释: 有三种方法可以爬到楼顶。
1. 1 阶 + 1 阶 + 1
2. 1 阶 + 2
3. 2 阶 + 1

Solution

参考**@覃超**的思路

  • 递归解法,时间复杂度为 O(2^n^)
1
2
3
4
5
6
7
# @lc code=start
class Solution:
def climbStairs(self, n: int) -> int:
if n <=2:
return n
return self.climbStairs(n-1)+self.climbStairs(n-2)
# @lc code=end
  • 打印爬楼梯步骤
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution:
def climbStairs(self, n: int) -> int:

self._dfs(n, [])

def _dfs(self, n, res):
if n>=0:
if n == 0:
print(res)

self._dfs(n-1, res+[1])
self._dfs(n-2, res+[2])

n = 5
s = Solution()
s.climbStairs(n)

动态规划

  • 记忆化搜索,自顶向下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// @lc code=start
class Solution {
private:
vector<int> memo;

int dp(int n){
if(n==0 || n==1)
return 1;

if(memo[n]==-1)
memo[n] = dp(n-1)+dp(n-2);
return memo[n];
}

public:
int climbStairs(int n) {
memo = vector<int>(n+1, -1);
int res = dp(n);
return res;
}
};
// @lc code=end
  • 自底向上
1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int climbStairs(int n) {
vector<int> memo(n+1, -1);
memo[0] = 1;
memo[1] = 1;
for(int i=2; i<=n; ++i){
memo[i] = memo[i-1] + memo[i-2];
}
return memo[n];
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!