题目
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?
答案
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
dp[m - 1][n - 1] = 1;
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int right_paths = 0, down_paths = 0;
// Skip finish grid
if(i == m - 1 && j == n - 1) continue;
// right
if(j < n - 1)
right_paths = dp[i][j + 1];
// down
if(i < m - 1)
down_paths = dp[i + 1][j];
dp[i][j] = right_paths + down_paths;
}
}
return dp[0][0];
}
}
``