Skip to content

Commit c2476e4

Browse files
committed
Add solution 062
1 parent 954a408 commit c2476e4

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ Complete solutions to Leetcode problems, updated daily.
3030
| 002 | [Add Two Numbers](https://github.com/yanglbme/leetcode/tree/master/solution/002.Add%20Two%20Numbers) | `Linked List`, `Math` |
3131
| 019 | [Remove Nth Node From End of List](https://github.com/yanglbme/leetcode/tree/master/solution/019.Remove%20Nth%20Node%20From%20End%20of%20List) | `Linked List`, `Two Pointers` |
3232
| 024 | [Swap Nodes in Pairs](https://github.com/yanglbme/leetcode/tree/master/solution/024.Swap%20Nodes%20in%20Pairs) | `Linked List` |
33+
| 062 | [Unique Paths](https://github.com/yanglbme/leetcode/tree/master/solution/062.Unique%20Paths) | `Array`, `Dynamic Programming` |
3334
| 082 | [Remove Duplicates from Sorted List II](https://github.com/yanglbme/leetcode/tree/master/solution/082.Remove%20Duplicates%20from%20Sorted%20List%20II) | `Linked List` |
3435

3536

solution/062.Unique Paths/README.md

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
## 不同路径
2+
### 题目描述
3+
4+
一个机器人位于一个 m x n 网格的左上角 (起始点在下图中标记为“Start” )。
5+
6+
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为“Finish”)。
7+
8+
问总共有多少条不同的路径?
9+
10+
![robot_maze](http://p9ucdlghd.bkt.clouddn.com/robot_maze.png)
11+
12+
例如,上图是一个 7 x 3 的网格。有多少可能的路径?
13+
14+
说明:m 和 n 的值均不超过 100。
15+
16+
示例 1:
17+
```
18+
输入: m = 3, n = 2
19+
输出: 3
20+
解释:
21+
从左上角开始,总共有 3 条路径可以到达右下角。
22+
1. 向右 -> 向右 -> 向下
23+
2. 向右 -> 向下 -> 向右
24+
3. 向下 -> 向右 -> 向右
25+
```
26+
27+
示例 2:
28+
```
29+
输入: m = 7, n = 3
30+
输出: 28
31+
```
32+
33+
### 解法
34+
在网格中,最左侧和最上方每个格子均只有一条可能的路径能到达。而其它格子,是它“左方格子的路径数+上方格子的路径数之和”(递推式)。开辟一个二维数组存放中间结果。
35+
36+
```java
37+
class Solution {
38+
public int uniquePaths(int m, int n) {
39+
int[][] res = new int[n][m];
40+
for (int i = 0; i < m; ++i) {
41+
res[0][i] = 1;
42+
}
43+
for (int i = 1; i < n; ++i) {
44+
res[i][0] = 1;
45+
}
46+
for (int i = 1; i < n; ++i) {
47+
for (int j = 1; j < m; ++j) {
48+
res[i][j] = res[i - 1][j] + res[i][j - 1];
49+
}
50+
}
51+
return res[n - 1][m - 1];
52+
}
53+
}
54+
```
+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
public int uniquePaths(int m, int n) {
3+
int[][] res = new int[n][m];
4+
for (int i = 0; i < m; ++i) {
5+
res[0][i] = 1;
6+
}
7+
for (int i = 1; i < n; ++i) {
8+
res[i][0] = 1;
9+
}
10+
for (int i = 1; i < n; ++i) {
11+
for (int j = 1; j < m; ++j) {
12+
res[i][j] = res[i - 1][j] + res[i][j - 1];
13+
}
14+
}
15+
return res[n - 1][m - 1];
16+
}
17+
}

0 commit comments

Comments
 (0)