题目
题解
代码
方法一:
import java.util.*;
public class code62 {
public static int uniquePaths(int m, int n) {
int N = m + n - 2;
int K = m - 1;
long res = 1;
for (int i = 1; i <= K; i++) {
res = res * (N - K + i) / i;
}
return (int) res;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int m = sc.nextInt();
int n = sc.nextInt();
int ans = uniquePaths(m, n);
System.out.println(ans);
}
}
}
方法二:
import java.util.*;
public class code62 {
public static int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
// 构造矩阵
int dp[][] = new int[m][n];
// 第一列只有一种方式行走
for (int i = 0; i < m; i++) {
dp[i][0] = 1;// 细节问题,假如只有一个点,那么到达的路径是 1
}
// 第一行只有一种方式行走
for (int j = 0; j < n; 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];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
int m = sc.nextInt();
int n = sc.nextInt();
int ans = uniquePaths(m, n);
System.out.println(ans);
}
}
}