Science and Technology Shang Dynasty 2020 autumn direction recruit java programming written questions

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Miaoshuowen/article/details/101645970

Input n, m integers two, seeking a ball grid from the m * n from the left to bottom right in a total of several paths, can only go to the right or down a grid, can not go back.
1 idea: recursion
as a depth-first traversal tree
Note the border, because it is within walking grid, so narrow in the case of the sideline to go
Code:

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);
		}
	}
}

Thinking 2:
We can upper left corner of the board is considered as two-dimensional coordinates (0,0), the lower right corner of the board is regarded as two-dimensional coordinates (M, N) (the coordinate system for the unit length becomes small squares length)
represents the total number of moves moved to the coordinate f (i, j), where 0 = <i, j <= n, provided f (m, n) representative of the coordinates (0, 0 with f (i, j)) method moved to the coordinate (m, n), then

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

Then the state transition equation of state f (i, j) is:

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

Code:

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 ];
	}
}

Guess you like

Origin blog.csdn.net/Miaoshuowen/article/details/101645970