Blue Bridge Pascal's Triangle JAVA fill in the blank

Pascal's Triangle, also known as Pascal's triangle, you can see a lot of the number of relations is very important.

Line 0: 1
Line 1: 1 1
Line 2: 121
Line 3: 1331
Line 4: 1 4 6 4 1
5, line: 15101051
Line 6: 1 . 6 15 20 15 1. 6
subject to the output 15 and 20 of the
element 1 are on both sides of the intermediate element and the element is the top left corner and top right corner of the element.

We agreed, line number, column number are from 0 count.
So: the second element 6 on line 15, the third element 20 is

Intuitively, it is necessary to open up a two-dimensional array, in fact, one-dimensional arrays can also do the job.
The following procedure is to use a one-dimensional array of "maneuvers" of the solution.
Ideas: from left to right, may change the number, and from right to left to push the problem does not occur, so we can reverse extrapolation to complete this question! !
Key: for (int q = 1; q <p; q ++); this should be our first thought, but the result is wrong, so I think the idea! !


public class Main{
	// 杨辉三角形的第row行第col列
	static long f(int row, int col) {
		if (row < 2)
			return 1;
		if (col == 0)
			return 1;
		if (col == row)
			return 1;

		long[] a = new long[row + 1];
		a[0] = 1;
		a[1] = 1;

		int p = 2;

		while (p <= row) {
			a[p] = 1;
			for (int q = p - 1; q >= 1; q--)     //填空位置
				a[q] = a[q] + a[q - 1];
			p++;
		}

		return a[col];
	}

	public static void main(String[] args) {
		System.out.println(f(6, 2));
		System.out.println(f(6, 3));
	}
}

Small Theater: mass production of clouds in the world, we have to continue to run.

Published 71 original articles · won praise 68 · views 8137

Guess you like

Origin blog.csdn.net/weixin_43771695/article/details/104553366