题目
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.
分析
根据题意,机器人每次只能向右走或向下走,那么机器人每走一步所经的路径数可以由其上一步的路径数决定,而上一步有两种可能,一种可能是上一步为其左边的格子,另一种可能是上一步为其上边的格子,这很显然是一个动态规划问题。设机器人到达位置(i, j)的路径数为f(i, j),则f(i, j)=f(i-1, j) + f(i, j-1),注意这里要将每一个格子的路径数初始化为1。算法复杂度为O(m*n)。
解答
class Solution { public: int uniquePaths(int m, int n) { vector<vector<int> > grid(m,vector<int> (n,1)); for(int i=1;i<m;i++){ for(int j=1;j<n;j++){ grid[i][j]=grid[i-1][j]+grid[i][j-1]; } } return grid[m-1][n-1]; } };