赞
踩
返回结果
思路一:
将右下角看做原点(0, 0),左上角看做坐标(m, n),从(m, n)—>(0, 0)就分两步走:
f(m, n - 1)—>(0, 0) 或f(m - 1, n)—>(0, 0)
注意:但凡是触碰到边界,f(x, 0)或者f(0,x)都只有一条直路可走
f(m, n) = f(m, n - 1) + f(m - 1, n)
- import java.util.Scanner;
-
- public class Main
- {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNext())
- {
- int n = scanner.nextInt();
- int m = scanner.nextInt();
- System.out.println(getPath(n, m));
- }
- }
- public static int getPath(int n, int m)
- {
- if (n == 0 || m == 0)
- return 1;
- return getPath(n - 1, m) + getPath(n, m - 1);
- }
- }

思路二:
n个格子就有n + 1条线
- import java.util.Scanner;
-
- public class Main
- {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- while (scanner.hasNext())
- {
- int n = scanner.nextInt();
- int m = scanner.nextInt();
- int[][] dp = new int[n + 1][m + 1];
- for (int i = 0; i <= n; i++)
- {
- for (int j = 0; j <= m; j++)
- {
- if (i == 0 && j == 0)
- dp[i][j] = 1;
- else if (i == 0)
- dp[i][j] = dp[i][j - 1];
- else if (j == 0)
- dp[i][j] = dp[i - 1][j];
- else
- dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
- }
- }
- System.out.println(dp[n][m]);
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。