Skip to content

Commit db167ac

Browse files
committed
feat: add [70] 爬楼梯
1 parent b86c96b commit db167ac

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

70.爬楼梯.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* @lc app=leetcode.cn id=70 lang=typescript
3+
*
4+
* [70] 爬楼梯
5+
*/
6+
7+
// @lc code=start
8+
function climbStairs(n: number): number {
9+
if (n <= 3) return n
10+
11+
// 从第 4 步开始走,所以构造 n-1=3, n-2=2
12+
let n2 = 2 // n-2
13+
let n1 = 3 // n-1
14+
let step = 3
15+
16+
let sum = 0
17+
while (step < n) {
18+
// n = n-1 + n-2
19+
sum = n1 + n2
20+
n2 = n1 // 由于往前走了一位,所以将 n-2 变成前一个 n-1
21+
n1 = sum // 由于往前走了一位,所以将 n-1 变成当前项 n
22+
step++
23+
}
24+
return sum
25+
};
26+
// @lc code=end
27+
28+
/**
29+
* 0 -> 0
30+
* 1 -> 1
31+
* 2 -> 2
32+
* 3 -> 3
33+
* 4 -> 5 1111,112,121,211,22
34+
* 5 -> 8 11111,2111,221,212,1211,122,1121,1112
35+
*/

0 commit comments

Comments
 (0)