问题描述:
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?
一个机器人,在m*n方格的左上角,每次只能向下走或者向右走,要到达右下角,有多少种走法?
问题求解:
path[i][j]表示要到达(i,j)处所有可能的步数。要到达(i,j)处有两种可能:
(1)从(i-1,j)处向下走一步。
(2)从(i,j-1)处向右走一步。
得到状态转移方程:
path[i][j] = path[i-1][j]+path[i][j-1];
并且:path[i][0] = 1;path[0][j] = 1;
代码如下:
class Solution {
public:
int uniquePaths(int m, int n) {
int path[m][n];
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(i==0 || j==0) path[i][j]=1;//无论目标点再第一行或第一列都只有一种可能
else
{//path[i][j]有2种可能:1、(i-1,j)处向下走。2、(i,j-1)处向右走
path[i][j] = path[i-1][j]+path[i][j-1];
}
}
}
return path[m-1][n-1];
}
};