题目:
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?
题解:
利用动态规划,列出公式 P[i][j]=P[i-1][j]+P[i][j-1],P[i][j]表示走到第i行第j列的路径数目,所以走到第i行第j列的路径数目=走到第i-1行第j列的路径数目+走到第i行第j-1列的路径数目。
答案:
class Solution {
public:
int uniquePaths(int m, int n) {
int P[101][101];
P[1][1]=1;
for (int i=2; i<=n; i++)
{
P[1][i]=1;
}
for (int i=2; i<=m; i++)
{
P[i][1]=1;
}
for (int i=2; i<=m; i++)
{
for (int j=2; j<=n; j++)
{
P[i][j]=P[i-1][j]+P[i][j-1];
}
}
return P[m][n];
}
};