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?
思路:
很朴素,除了最上边一行和最左边一列,路径数跟左边和上边的路径数有关系。于是不难写出:
grid[i][j] = grid[i - 1][j] + grid[i][j-1];
int uniquePaths(int m, int n) { if (m <= 0 || n <= 0)return 0; vector<vector<int>>grid(m,vector<int>(n)); grid[0][0] = 1; for (int i = 0; i < m;i++) { for (int j = 0; j < n;j++) { if (i ==0 && j != 0) { grid[i][j] = 1; } if (i != 0 && j == 0) { grid[i][j] = 1; } if (i != 0 && j != 0) { grid[i][j] = grid[i - 1][j] + grid[i][j-1]; } } } return grid[m-1][n-1]; }