File tree Expand file tree Collapse file tree 3 files changed +62
-0
lines changed
solution/70.Climbing Stairs Expand file tree Collapse file tree 3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change @@ -16,6 +16,7 @@ Complete solutions to Leetcode problems, updated daily.
16
16
| 007 | [ Reverse Integer] ( https://github.com/yanglbme/leetcode/tree/master/solution/007.Reverse%20Integer ) | ` Math ` |
17
17
| 013 | [ Roman to Integer] ( https://github.com/yanglbme/leetcode/tree/master/solution/013.Roman%20to%20Integer ) | ` Math ` , ` String ` |
18
18
| 021 | [ Merge Two Sorted Lists] ( https://github.com/yanglbme/leetcode/tree/master/solution/021.Merge%20Two%20Sorted%20Lists ) | ` Linked List ` |
19
+ | 070 | [ Climbing Stairs] ( https://github.com/yanglbme/leetcode/tree/master/solution/070.Climbing%20Stairs ) | ` Dynamic Programming ` |
19
20
| 083 | [ Remove Duplicates from Sorted List] ( https://github.com/yanglbme/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List ) | ` Linked List ` |
20
21
| 198 | [ House Robber] ( https://github.com/yanglbme/leetcode/tree/master/solution/198.House%20Robber ) | ` Dynamic Programming ` |
21
22
| 203 | [ Remove Linked List Elements] ( https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements ) | ` Linked List ` |
Original file line number Diff line number Diff line change
1
+ ## 爬楼梯
2
+ ### 题目描述
3
+
4
+ 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
5
+
6
+ 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
7
+
8
+ 注意:给定 n 是一个正整数。
9
+
10
+ 示例 1:
11
+ ```
12
+ 输入: 2
13
+ 输出: 2
14
+ 解释: 有两种方法可以爬到楼顶。
15
+ 1. 1 阶 + 1 阶
16
+ 2. 2 阶
17
+ ```
18
+
19
+ 示例 2:
20
+ ```
21
+ 输入: 3
22
+ 输出: 3
23
+ 解释: 有三种方法可以爬到楼顶。
24
+ 1. 1 阶 + 1 阶 + 1 阶
25
+ 2. 1 阶 + 2 阶
26
+ 3. 2 阶 + 1 阶
27
+ ```
28
+
29
+ ### 解法
30
+ 爬上 1 阶有 1 种方法,爬上 2 阶有 2 种方法,爬上 n 阶 f(n) 有 f(n - 1) + f(n - 2) 种方法。可以利用数组记录中间结果,防止重复计算。
31
+
32
+ ``` java
33
+ class Solution {
34
+ public int climbStairs (int n ) {
35
+ if (n < 3 ) {
36
+ return n;
37
+ }
38
+ int [] res = new int [n + 1 ];
39
+ res[1 ] = 1 ;
40
+ res[2 ] = 2 ;
41
+ for (int i = 3 ; i < n + 1 ; ++ i) {
42
+ res[i] = res[i - 1 ] + res[i - 2 ];
43
+ }
44
+ return res[n];
45
+ }
46
+ }
47
+ ```
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int climbStairs (int n ) {
3
+ if (n < 3 ) {
4
+ return n ;
5
+ }
6
+ int [] res = new int [n + 1 ];
7
+ res [1 ] = 1 ;
8
+ res [2 ] = 2 ;
9
+ for (int i = 3 ; i < n + 1 ; ++i ) {
10
+ res [i ] = res [i - 1 ] + res [i - 2 ];
11
+ }
12
+ return res [n ];
13
+ }
14
+ }
You can’t perform that action at this time.
0 commit comments