方法一 DFS深度优先
import java.util.Scanner;
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int result = 0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextInt()) { // 注意 while 处理多个 case
int a = in.nextInt();
int b = in.nextInt();
find(a, b, 0, 0);
System.out.println(find2(a, b));
}
}
/**
DFS 深度优先
*/
public static void find(int a, int b, int cow, int row) {
if (cow == a && row == b) {
result = result + 1;
return;
}
if (cow + 1 <= a) {
find(a, b, cow + 1, row);
}
if (row + 1 <= b) {
find(a, b, cow, row + 1);
}
}
/**
动态,规划
*/
public static int find2(int a, int b) {
int[][] dp = new int[a + 1][b + 1];
dp[0][0] = 0;
for (int i = 0; i <= a; i++) {
for (int j = 0; j <= b; j++) {
if (i == 0 || j == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
}
}
}
return dp[a][b];
}
}