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问题,构造一个m*n矩阵,用step[row][col]代表走到(i,j)节点的多种线路数,因为只能往右或者下移动,所以矩阵的第一行(只能往右移动)和第一列(只能往下移动)为1.其它节点的线路数为
steps[i][j] = steps[i - 1][j] + steps[i][j - 1];
1 public int uniquePaths(int m, int n) { 2 if (m == 0 || n == 0) return 0; 3 if (m == 1 || n == 1) return 1; 4 int[][] steps = new int[m][n]; 5 for (int i = 0; i < m; i++) 6 for (int j = 0; j < n; j++) { 7 if (i==0 || j==0) steps[i][j] = 1; 8 else steps[i][j] = steps[i - 1][j] + steps[i][j - 1]; 9 } 10 return steps[m - 1][n - 1]; 11 }