-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclimbing-stairs.cpp
More file actions
52 lines (42 loc) · 1.05 KB
/
Copy pathclimbing-stairs.cpp
File metadata and controls
52 lines (42 loc) · 1.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// Created by Chenguang Wang on 2024/1/20.
//
// https://leetcode.cn/problems/climbing-stairs/description/
class Solution {
public:
int climbStairs(int n) {
int n0 = 0, n1 = 0, result = 1;
for (int i = 1; i <= n; ++i) {
n0 = n1;
n1 = result;
result = n0 + n1;
}
return result;
}
int climbStairs1(int n) {
if (n == 0 || n == 1) {
return 1;
}
int a = 1; // f(n-2)
int b = 1; // f(n-1)
for (int i = 2; i <= n; ++i) {
int c = a + b;
a = b;
b = c;
}
return b;
}
int climbStairs2(int n) {
// 边界条件
if (n <= 1) {
return 1;
}
int prev1 = 1, prev2 = 1; // 初始状态:f(0) 和 f(1)
for (int i = 2; i <= n; ++i) {
int current = prev1 + prev2; // 当前状态
prev2 = prev1; // 更新 prev2
prev1 = current; // 更新 prev1
}
return prev1; // 最终结果
}
};