c ++ / c language Pascal's Triangle (explain in detail).

Pascal's triangle in the form as shown below

Here Insert Picture Description
But is there any way to play this map do?
We can fill all vacancies to zero, and to find the law.

0 after fill gaps as shown in FIG.

Here Insert Picture Description
Here Insert Picture Description
We put the number of rows and columns are set to r and c;

In the figure above we can find:

When r = 4, c = 9;

When r = 7, c = 15;

Such laws can be obtained;

c = 2 * r +1 and the first line of a first index number is rounded down to give c / 2

In addition, we can also see:
two numbers of a number of these oblique line of the previous row and the sum.
If the number used to store all the matrix [r] [c], this array, i, j, respectively for the rows and columns, this rule can be obtained:

matrix [ i ] [ j ] = matrix [ i-1 ] [ j-1 ]+ matrix [ i-1 ] [ j+1 ] 。

The code can be obtained as follows:

#include<bits/stdc++.h>
using namespace std;
int main() {
//	int r,c;//分别表示r行和c列。
	int r,c;
	cin>>r;
	c=2*r+1;//列数与行数的关系。
	int r_one=c/2;//第一行的第一个数。(以第一行的第一个数为起点)
	int matrix[r][c]; //把所有r行c列的所有点都标为0。
	memset(matrix,0,sizeof(matrix));//这里是把二维数组所有项都初始化为零
	matrix[0][r_one]=1;
	for(int i=1; i<r; i++) {
		for(int j=1; j<c; j++) {
			matrix[i][j]=matrix[i-1][j-1]+matrix[i-1][j+1];
		}
	}
	for(int i=0; i<r; i++) {
		for(int j=0; j<c; j++) {
			if(matrix[i][j]==0)
				printf(" \t");
			else
				printf("%d\t",matrix[i][j]);
		}
		cout<<endl;
	}
	return 0;
}

Take in bloom.

Released eight original articles · won praise 8 · views 200

Guess you like

Origin blog.csdn.net/xzy15703841578/article/details/105375798