友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
62. Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28
思路分析
-
一刷
-
二刷
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
53
54
55
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2019-10-26 22:56
*/
public int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
int[] row = new int[n];
Arrays.fill(row, 1);
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
row[j] = row[j - 1] + row[j];
}
}
return row[n - 1];
}
/**
* timeout
*/
public int uniquePathsBottomUp(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
if (m == 1 || n == 1) {
return 1;
}
return uniquePathsBottomUp(m - 1, n) + uniquePathsBottomUp(m, n - 1);
}
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Unique Paths.
* <p>
* Memory Usage: 33 MB, less than 5.10% of Java online submissions for Unique Paths.
*/
public int uniquePathsMatrix(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
int[][] paths = new int[m][n];
for (int i = 0; i < m; i++) {
paths[i][0] = 1;
}
for (int i = 1; i < n; i++) {
paths[0][i] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
paths[i][j] = paths[i - 1][j] + paths[i][j - 1];
}
}
return paths[m - 1][n - 1];
}
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
/**
* @author D瓜哥 · https://www.diguage.com
* @since 2024-09-12 15:16:31
*/
public int uniquePaths(int m, int n) {
// 1. dp 表示走到某个节点一共有多少路径
int[][] dp = new int[m][n];
// 3. 第一行只有一种走法
for (int i = 0; i < m; i++) {
dp[i][0] = 1;
}
// 3. 第一列也只有一种走法。
for (int i = 0; i < n; i++) {
dp[0][i] = 1;
}
// 4. 遍历顺序:从左上逐步向右下遍历
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
// 2. 由于只能从上或者从左走过来,
// 那么路径数量就是两个节点相加
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}