62. Unique Paths

每日一题 2019 - 04 - 05

题目:

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?

img
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:

1
2
3
4
5
6
7
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:

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

解法:

这是一道基础的动态规划类的问题,需要找出对应的等式递推关系就可以解决问题;

思路:

  • 到达[i,j]位置的 robot 必然是从 [i,j-1] 或者 [i-1,j] 位置到来,那么证明到这个位置可以有 dp[i-1,j] + [i,j-1] 种走法

所以从上可知:递推公式为 dp[i,j] = dp[i-1,j] + dp[i,j-1]


代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int uniquePaths(int m, int n) {
int i,j;
int dp[m+1][n+1]; //表示 i 行 j 列的不同路径
for (i = 1,j = 1;j < n + 1;j++) {
dp[i][j] = 1;
}
for (i = 1,j = 1;i < m + 1;i++) {
dp[i][j] = 1;
}
for (i = 2;i < m + 1;i++)
{
for (j = 2;j < n + 1;j++)
{
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m][n];
}
};
0%
undefined