1. Description
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?
2. Example
Given m = 3, n = 7
Return 28
3. Explanation
DP
Let dp[i][j] stands for the minimum sum of all numbers along its path when arrive grid (i,j)
(1). init first column
for(i : 0 \rightarrow M)
dp[i][0] = 1
(2). init first row
for(j : 0 \rightarrow N)
dp[0][j] = 1
(3). for(i : 1 \rightarrow M; j : 1 \rightarrow N)
dp[i][j] = dp[i-1][j] + dp[i][j-1]
4. Code
public int uniquePaths(int m, int n) {
if (m < 1 || n < 1) {
return 0;
}
int[][] dp = new int[m][n];
dp[0][0] = 1;
for (int i = 1; i < m; i++) {
dp[i][0] = dp[i - 1][0];
}
for (int j = 1; j < n; j++) {
dp[0][j] = dp[0][j - 1];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
Comments | NOTHING