LeetCode OJ-62. Unique Paths(DP)
题目描述
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 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Subscribe to see which companies asked this question
题目理解
在一个m*n的方格矩形中,要从(0, 0)移动到(m - 1, n - 1),求不同的路径总共有多少种。
dfs可以寻路,但去重很麻烦。这里要明确,无障碍物,每一个格子都能走到,且仅能往右和往下走。所以,我们可以确定,如果一个格子左边没有格子,或者上边没有格子,那到达该格子的路径就只会有1条。
这里使用动态规划会比较容易处理,定义状态dp[i][j]为到达(i, j)时,有多少条不同的路径,对于没有左边格子或没有上边格子的位置,dp值就为1,而其他格子就依赖于到达其左边格子的不同路径数与其上边格子的不同路径数之和,状态转移方程可写作dp[i][j] = { 1, i = 0 || j = 0 } | { dp[i][j - 1] + dp[i - 1][j], i > 0 && j > 0 }。由此可得代码:
Code
const int g_kMaxSize = 101;
int g_res[g_kMaxSize][g_kMaxSize] = { 0 };
void dp(int m, int n)
{
int i, j;
for (i = 0; i < m; ++i) {
for (j = 0; j < n; ++j) {
if (i == 0 || j == 0) {
g_res[i][j] = 1;
}
else {
g_res[i][j] = g_res[i - 1][j] + g_res[i][j - 1];
}
}
}
}