Pascal's triangle
Pascal's triangle is made up of a triangular array filled with binomial coefficients. binomial coefficients occur in binomial expansion. the ith row of pascal's triangle represents coefficients of (a+b)^(i-1) binomial expansion coefficients.
7-row pascal's triangle.
Read Also:Prefix Sum of 3D array
Example:
Input:
N = 9;
Output:
pascal's triangle of 9 Rows...
rows 1 : 1
rows 2 : 1 1
rows 3 : 1 2 1
rows 4 : 1 3 3 1
rows 5 : 1 4 6 4 1
rows 6 : 1 5 10 10 5 1
rows 7 : 1 6 15 20 15 6 1
rows 8 : 1 7 21 35 35 21 7 1
rows 9 : 1 8 28 56 70 56 28 8 1
Explanation:
Create two arrays temp[] with no element and arr[] with element equals to 1.
Iterate process N times for N rows.
- print arr[]
- Add 1 to back of temp[]
- Iterate form j = 0 to arr.size()-1 and add arr[j]+arr[j+1] to back of temp[].
- Add again 1 to back of temp[]
this process print N rows of Pascal's triangle.
Implementation:
C++ Implementation:
// C++ code for Pascal's Triangle
#include <bits/stdc++.h>
using namespace std;
// printPascal() function for printing pascal's triangle.
void printPascal(int N)
{
// declaring 2 array
vector<int> arr = {1}; // current row.
vector<int> temp;
cout << "pascal's triangle of " << N << " Rows..." << endl;
// calculating next rows.
for (int i = 0; i < N; i++)
{
// printing current row.
cout << "rows " << i + 1 << " : ";
for (int j = 0; j < arr.size(); j++)
{
cout << arr[j] << ' ';
}
cout << endl;
// calculating next rows.
temp.push_back(1);
for (int j = 0; j < arr.size() - 1; j++)
{
temp.push_back(arr[j] + arr[j + 1]);
}
temp.push_back(1);
// copy next row to current row.
arr = temp;
// initialize temp to empty array.
temp = vector<int>();
}
}
// Driver code
int main()
{
int N = 9;
printPascal(N);
return 0;
}
Python Implementation:
# python code for Pascal's Triangle
# printPascal() function for printing pascal's triangle.
def printPascal(N):
# declaring 2 array
arr = [1]
temp = []
print("pascal's triangle of", N, "Rows...")
# calculating next rows.
for i in range(N):
# printing current row.
print("rows", i+1, end=" : ")
for j in range(len(arr)):
print(arr[j], end=' ')
print()
# calculating next rows.
temp.append(1)
for j in range(len(arr)-1):
temp.append(arr[j] + arr[j + 1])
temp.append(1)
# copy next row to current row.
arr = temp
# initialize temp to empty array.
temp = []
# Driver code
N = 9
printPascal(N)
Output:
pascal's triangle of 9 Rows...
rows 1 : 1
rows 2 : 1 1
rows 3 : 1 2 1
rows 4 : 1 3 3 1
rows 5 : 1 4 6 4 1
rows 6 : 1 5 10 10 5 1
rows 7 : 1 6 15 20 15 6 1
rows 8 : 1 7 21 35 35 21 7 1
rows 9 : 1 8 28 56 70 56 28 8 1
Time Complexity: O(N^2)
Auxiliary Space: O(N)Read Also:Prefix Sum of 2D Array
0 Comments
If you have any doubt let me know.