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?

Example 1:

Input: m = 3, n = 7
Output: 28

Example 2:

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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down

思路

由于机器人只能向右走和向下走,所以:

  1. 地图的第一行和第一列的走法数都是 1
  2. 其他任意一点的走法数是: dp[i][j] = dp[i-1][j] + dp[i][j-1]

Python

1
2
3
4
5
6
7
8
def uniquePaths(m: int, n: int) -> int:
path = [[1 if i==0 or j == 0 else 0 for j in range(m)] for i in range(n)]

for i in range(1, n):
for j in range(1, m):
path[i][j] = path[i-1][j] + path[i][j-1]

return path[n-1][m-1]

Golang

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func uniquePaths(m int, n int) int {
dp := make([][]int, n)
for i := 0; i < n; i++ {
dp[i] = make([]int, m)
}
for i := 0; i < m; i++ {
dp[0][i] = 1
}
for i := 0; i < n; i++ {
dp[i][0] = 1
}
for i := 1; i < n; i++ {
for j := 1; j < m; j++ {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
return dp[n-1][m-1]
}

Rust

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pub fn unique_paths(m: i32, n: i32) -> i32 {
let m: usize = m as usize;
let n: usize = n as usize;
let mut paths: Vec<Vec<i32>> = vec![vec![0; m]; n];

for i in 0..m {
for j in 0..n {
if (i == 0 || j == 0){
paths[j][i] = 1;
}
}
}

for i in 1..m {
for j in 1..n {
paths[j][i] = paths[j-1][i] + paths[j][i-1];
}
}
return paths[n-1][m-1];
}

C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int uniquePaths(int m, int n){
int paths[n][m];

for (int j=0; j<n; j++) {
for (int i=0; i<m; i++) {
if (i == 0 || j == 0) {
paths[j][i] = 1;
} else {
paths[j][i] = 0;
}
}
}

for (int j=1; j<n; j++) {
for (int i=1; i<m; i++) {
paths[j][i] = paths[j-1][i] + paths[j][i-1];
}
}

return paths[n-1][m-1];
}

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public int uniquePaths(int m, int n) {
int[][] paths = new int[n][m];

for (int i=0; i < n; i++) {
for (int j=0; j < m; j++) {
if (i == 0 || j == 0) {
paths[i][j] = 1;
} else {
paths[i][j] = 0;
}
}
}

for (int i=1; i < n; i++) {
for (int j=1; j < m; j++) {
paths[i][j] = paths[i-1][j] + paths[i][j-1];
}
}

return paths[n-1][m-1];
}

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var uniquePaths = function(m, n) {
var paths = new Array();

for (var j=0; j<n; j++) {
paths[j] = new Array();

for (var i=0; i<m; i++) {
if (i == 0 || j ==0) {
paths[j][i] = 1;
} else {
paths[j][i] = 0;
}
}
}

for (var j=1; j<n; j++) {
for (var i=1; i<m; i++) {
paths[j][i] = paths[j-1][i] + paths[j][i-1];
}
}

return paths[n-1][m-1]
};

Submissions

Reference 参考

[1] 62. Unique Paths