The output print Yang Hui's triangle is an example of a queue implementation.
The characteristics of the Yang Hui's triangle we all know that the number of each row is equal to the sum of about two digits of its upper layer.
Through the queue, save the number of the output to the team, because the following numbers need to use the previous number and operation. The first line of 1 is the default direct queue output, the last 1 of each row is also the default output, it does not relate to the previous number. Other numbers can be obtained by the sum of the team head elements and the next element. Note that the first element is obtained by adding a 0 to the top 1 and to the left of it.
#include <iostream>
#include <queue>
using namespace std;
void Print_triangle (int n) {
queue<int>q;
for (int i=0;i<2*n-1;i++) //control output, beautiful
cout<< "";
cout<<1<< "" <<endl; The output of the first row of 1
q.push (1);
int s1,s2;
for (int i=2;i<=n;i++) {
for (int k=0;k<2*n-i;k++) //control output, beautiful
cout<< "";
S1 = 0;
for (int j=1;j<=i-1;j++) {
s2 = Q.front ();
Q.pop (); Out team
cout<<s1+s2<< "";
Q.push (S1+S2);
S1 = s2; S1 retains the previous number
}
cout<<1<<endl; Outputs the last 1
q.push (1) of each line
;
}
int main () {
int n;
cin>>n; Enter the number of rows
print_triangle (n) for the Yang Hui's triangle to be obtained;
return 0;
}
At that time she asked me, can not read the code, I write it myself. I think, do not read the code, I can completely another simple approach to solve.
The array a[i][j] represents the number in column J of line I, except for the number of individual positions where the default assignment is 1, other numbers can be in the following formula:
A[I][J] = A[i-1][j-1] + a[i-1][j]
That is, the number of rows equals the sum of two digits on the shoulder of the previous line, and then the output is.
#include <iostream>
using namespace std;
int main () {
int a[10][10]; Save the element for Yang Hui's triangle for
(int i=1;i<10;i++) {for
(int j=1;j<=i;j++) {
if (i==1&&j==1)
a[i][j] = 1 ;
else{
if (j==1 | | j==i)
A[I][J] = 1;
else
a[i][j] = a[i-1][j-1] + a[i-1][j];
}
}
int n;
cin>>n;
for (int i=1;i<=n;i++) {
for (int k=0;k<2*n-i;k++) //control output, beautiful
cout<< "";
for (int j=1;j<=i;j++) {
cout<<a[i][j]<< "";
}
cout<<endl;
}
return 0;
}