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.
分析:
這是一個基本的DP問題。首先,讓我們做一些觀察。
由於機器人只能左右移動,當它到達某個點時,只有兩種可能性:
它從上面到達那個點(向下移動到那個點);
它從左邊到達那個點(向右移動到那個點)。
因此,我們有以下狀態方程:假設到達一個點的路徑數(i,j)被表示爲p[ i ],很容易得出結論:P[i][j] = P[i - 1][j] + P[i][j - 1].。
上述方程的邊界條件發生在最左邊的列(P [i] [ j-1 ]不存在)和最上面的行(P [ i-1 ] [ J ]不存在)。這些條件可以通過初始化(預處理)來處理——對於所有有效的i,初始化P[0][j] = 1, P[i][0] = 1。注意,初始值是1而不是0!
現在我們可以寫如下代碼。
程序:
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int> > path(m, vector<int> (n, 1));
for (int i = 1; i < m; i++)
for (int j = 1; j < n; j++)
path[i][j] = path[i - 1][j] + path[i][j - 1];
return path[m - 1][n - 1];
}
};