2020商汤科技秋招java方向笔试编程题

输入n,m两个整数,求一个小球从m*n的格子中从左上角到右下角总共有几种路径,每次只能往下或者往右走一格,不能走回头路。
思路1:递归
当成深度优先遍历一颗树
注意边界,因为是格内走,所以在边线走的情况下缩小范围
代码:

public class Shangtang1 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int m = in.nextInt();
		int n = in.nextInt();
		in.close();
		Shangtang1 test = new Shangtang1();

		System.out.println(test.method(n-1 , m-1 ));
	}

	private int method(int n, int m) {
		if (n > 0 && m > 0) {
			return method(n - 1, m) + method(n, m - 1);
		} else if (n == 0 || m == 0) {
			return 1;
		} else {
			return method(n - 1, m) + method(n, m - 1);
		}
	}
}

思路2:
我们可以把棋盘的左上角看做二维坐标的原点(0,0),把棋盘的右下角看做二维坐标(M,N)(坐标系的单位长度为小方格的变长)
用f(i,j)表示移动到坐标f(i,j)的走法总数,其中0=

f(m,n)=f(m-1,n)+f(m,n-1).

于是状态f(i,j)的状态转移方程为:

f(i,j)=f(i-1,j)+f(i,j-1) if i,j>0

f(i,j)=f(i,j-1) if i=0

f(i,j)=f(i-1,j) if j=0

代码:

public class Shangtang1 {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int m = in.nextInt();
		int n = in.nextInt();
		in.close();
		Shangtang1 test = new Shangtang1();

		System.out.println(test.method2(n , m ));
	}
	private int method2(int n, int m) {
		int[][] a = new int[n][m];
		for (int i = 0; i < n; i++) {
			a[i][0] = 1;
		}
		for (int j = 0; j < m; j++) {
			a[0][j] = 1;
		}
		for (int k = 0; k < n - 1; k++) {
			for (int y = 0; y < m - 1; y++) {
				a[k + 1][y + 1] = a[k + 1][y] + a[k][y + 1];
			}
		}
		return a[n -1][m -1 ];
	}
}

你可能感兴趣的:(笔记)