Skip to content

Commit ec920b4

Browse files
committed
Add solution 070
1 parent c66482f commit ec920b4

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Complete solutions to Leetcode problems, updated daily.
1616
| 007 | [Reverse Integer](https://github.com/yanglbme/leetcode/tree/master/solution/007.Reverse%20Integer) | `Math` |
1717
| 013 | [Roman to Integer](https://github.com/yanglbme/leetcode/tree/master/solution/013.Roman%20to%20Integer) | `Math`, `String` |
1818
| 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` |
1920
| 083 | [Remove Duplicates from Sorted List](https://github.com/yanglbme/leetcode/tree/master/solution/083.Remove%20Duplicates%20from%20Sorted%20List) | `Linked List` |
2021
| 198 | [House Robber](https://github.com/yanglbme/leetcode/tree/master/solution/198.House%20Robber) | `Dynamic Programming` |
2122
| 203 | [Remove Linked List Elements](https://github.com/yanglbme/leetcode/tree/master/solution/203.Remove%20Linked%20List%20Elements) | `Linked List` |

solution/70.Climbing Stairs/README.md

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
```
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
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+
}

0 commit comments

Comments
 (0)