Address: https: //leetcode-cn.com/problems/unique-paths/
Method One: dynamic programming
-
Status:
dp[i][j]
represent walked coordinate(i, j)
the total number of paths; -
State transition equation: the idea is still classified discussions went coordinates
(i, j)
can be from the top down, you can also come from the left, it is the total sum of the two paths;
dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
-
Initialization: an array
dp
row 1 and column 1 had displayed value of 1; -
Output:
dp[m - 1][n - 1]
. -
The state of compression: You can scroll array, can also be compressed to just one-dimensional.
Java code:
import java.util.Arrays;
public class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
Arrays.fill(dp[0], 1);
for (int i = 1; i < m; i++) {
dp[i][0] = 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];
}
}
Initialization too much trouble, it can be considered "sentinel" writing, array dp
write a line, write one.
Java code:
import java.util.Arrays;
public class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m + 1][n + 1];
// 初始化的时候 dp[0][1] = 1; 或者 dp[1][0] = 1; 均可
dp[1][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dp[i + 1][j + 1] = dp[i][j + 1] + dp[i + 1][j];
}
}
return dp[m][n];
}
}
The state of compression.
Java code:
public class Solution {
public int uniquePaths(int m, int n) {
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
}
Method two: the number of combinations
Use the number of combinations to solve, went coordinates (m, n)
of the place, walk down the m - 1
grid, go to the right n - 1
format. We walked a total m + n - 2
grid.