leetcode-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?

unique-path
Above is a 3 x 7 grid. How many possible unique paths are there?

分析


动态规划,每一个位置的数量等于这个位置上方位置和左边位置数量相加。

解决方案1(python)


1
2
3
4
5
6
7
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
dp = [[1] * n] + [[1] + [0] * (n-1) for _ in range(m-1)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]

解决方案2(C++)


1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int> > table(m, vector<int>(n, 1));
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
table[i][j] = table[i-1][j] + table[i][j-1];
}
}
return table[m-1][n-1];
}
};

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func uniquePaths(m int, n int) int {
dp := make([][]int, m)
for i := range dp {
dp[i] = make([]int, n)
}

for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i == 0 || j == 0 {
dp[i][j] = 1
} else {
dp[i][j] = dp[i-1][j] + dp[i][j-1]
}
}
}
return dp[m-1][n-1]
}

相关问题


题目来源