The number of entries in every row is equal to row number (1-based). For example, the first row has "1", the second row has "1 1", the third row has "1 2 1",.. and so on. Every entry in a row is value of a Binomial Coefficient.
The value of ith entry in row number is nCi . The value can be calculated using following formula.
nCi = n! / (i! * (n-i)!) - ith element of nth row
Run a loop for each row of pascal's triangle i.e. 1 to n. For each row, loop through its elements and calculate their binomial coefficients as described in the approach.
C++
// Cpp program for Pascal's Triangle using Binomial// Coefficient in O(n^3) and O(1) Space#include<iostream>#include<vector>usingnamespacestd;intbinomialCoeff(intn,intk){intres=1;if(k>n-k)k=n-k;for(inti=0;i<k;++i){res*=(n-i);res/=(i+1);}returnres;}// Function to print first n rows// of Pascal's Trianglevector<vector<int>>printPascal(intn){vector<vector<int>>mat;// Iterate through every row and// print entries in itfor(introw=0;row<n;row++){// Every row has number of// integers equal to row// numbervector<int>arr;for(inti=0;i<=row;i++)arr.push_back(binomialCoeff(row,i));mat.push_back(arr);}returnmat;}intmain(){intn=5;vector<vector<int>>mat=printPascal(n);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<endl;}return0;}
Java
// Java program for Pascal's Triangle using Binomial// Coefficient in O(n^3) and O(1) Space importjava.util.*;classGfG{staticintbinomialCoeff(intn,intk){intres=1;if(k>n-k)k=n-k;for(inti=0;i<k;++i){res*=(n-i);res/=(i+1);}returnres;}// Function to print first n rows // of Pascal's Triangle staticList<List<Integer>>printPascal(intn){List<List<Integer>>mat=newArrayList<>();// Iterate through every row and// print entries in itfor(introw=0;row<n;row++){List<Integer>arr=newArrayList<>();for(inti=0;i<=row;i++)arr.add(binomialCoeff(row,i));mat.add(arr);}returnmat;}publicstaticvoidmain(String[]args){intn=5;List<List<Integer>>mat=printPascal(n);for(inti=0;i<mat.size();i++){for(intj=0;j<mat.get(i).size();j++){System.out.print(mat.get(i).get(j)+" ");}System.out.println();}}}
Python
# Python program for Pascal's Triangle using Binomial# Coefficient in O(n^3) and O(1) Space defbinomialCoeff(n,k):res=1ifk>n-k:k=n-kforiinrange(k):res*=(n-i)res//=(i+1)returnres# Function to print first n rows # of Pascal's Triangle defprintPascal(n):mat=[]# Iterate through every row and# print entries in itforrowinrange(n):arr=[]foriinrange(row+1):arr.append(binomialCoeff(row,i))mat.append(arr)returnmatn=5mat=printPascal(n)foriinrange(len(mat)):forjinrange(len(mat[i])):print(mat[i][j],end=" ")print()
C#
// C# program for Pascal's Triangle using Binomial// Coefficient in O(n^3) and O(1) Space usingSystem;usingSystem.Collections.Generic;classGfG{staticintbinomialCoeff(intn,intk){intres=1;if(k>n-k)k=n-k;for(inti=0;i<k;++i){res*=(n-i);res/=(i+1);}returnres;}// Function to print first n rows // of Pascal's Triangle staticList<List<int>>printPascal(intn){List<List<int>>mat=newList<List<int>>();// Iterate through every row and// print entries in itfor(introw=0;row<n;row++){List<int>arr=newList<int>();for(inti=0;i<=row;i++)arr.Add(binomialCoeff(row,i));mat.Add(arr);}returnmat;}staticvoidMain(){intn=5;List<List<int>>mat=printPascal(n);for(inti=0;i<mat.Count;i++){for(intj=0;j<mat[i].Count;j++){Console.Write(mat[i][j]+" ");}Console.WriteLine();}}}
JavaScript
// JavaScript program for Pascal's Triangle using Binomial// Coefficient in O(n^3) and O(1) Space functionbinomialCoeff(n,k){letres=1;if(k>n-k)k=n-k;for(leti=0;i<k;++i){res*=(n-i);res/=(i+1);}returnres;}// Function to print first n rows // of Pascal's Triangle functionprintPascal(n){constmat=[];// Iterate through every row and// print entries in itfor(letrow=0;row<n;row++){constarr=[];for(leti=0;i<=row;i++)arr.push(binomialCoeff(row,i));mat.push(arr);}returnmat;}constn=5;constmat=printPascal(n);for(leti=0;i<mat.length;i++){letline="";for(letj=0;j<mat[i].length;j++){line+=mat[i][j]+" ";}console.log(line);}
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time Complexity - O(n3) Auxiliary Space - O(1)
[Better Approach] Using Dynamic Programming
If we take a closer at the triangle, we observe that every entry is sum of the two values above it. So using dynamic programming we can createa 2D array that stores previously generated values. In order to generate a value in a line, we can use the previously stored values from array.
Pascal 's Triangle
Cases:
If row == 0 or row == i
arr[row][i] =1
Else:
arr[row][i] = arr[row-1][i-1] + arr[row-1][i]
C++
// Cpp program for Pascal’s Triangle Using Dynamic // Programming in O(n^2) time and O(n^2) extra space #include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>printPascal(intn){// An auxiliary array to store // generated pascal triangle valuesvector<vector<int>>mat;// Iterate through every line and // print integer(s) in itfor(introw=0;row<n;row++){// Every line has number of integers // equal to line numbervector<int>arr;for(inti=0;i<=row;i++){// First and last values in every row are 1if(row==i||i==0)arr.push_back(1);// Other values are sum of values just // above and left of aboveelsearr.push_back(mat[row-1][i-1]+mat[row-1][i]);}mat.push_back(arr);}returnmat;}intmain(){intn=5;vector<vector<int>>mat=printPascal(n);for(inti=0;i<mat.size();i++){for(intj=0;j<mat[i].size();j++){cout<<mat[i][j]<<" ";}cout<<endl;}return0;}
C
#include<stdio.h>#include<stdlib.h>int**printPascal(intn){// An auxiliary array to store // generated pascal triangle valuesint**mat=(int**)malloc(n*sizeof(int*));for(inti=0;i<n;i++){mat[i]=(int*)malloc((i+1)*sizeof(int));}// Iterate through every line and // print integer(s) in itfor(introw=0;row<n;row++){// Every line has number of integers // equal to line numberfor(inti=0;i<=row;i++){// First and last values in every row are 1if(row==i||i==0)mat[row][i]=1;// Other values are sum of values just // above and left of aboveelsemat[row][i]=mat[row-1][i-1]+mat[row-1][i];}}returnmat;}intmain(){intn=5;int**mat=printPascal(n);for(inti=0;i<n;i++){for(intj=0;j<=i;j++){printf("%d ",mat[i][j]);}printf("\n");}return0;}
Java
// Java program for Pascal’s Triangle Using Dynamic // Programming in O(n^2) time and O(n^2) extra space importjava.util.*;classGfG{staticList<List<Integer>>printPascal(intn){// An auxiliary array to store // generated pascal triangle valuesList<List<Integer>>mat=newArrayList<>();// Iterate through every line and // print integer(s) in itfor(introw=0;row<n;row++){// Every line has number of integers // equal to line numberList<Integer>arr=newArrayList<>();for(inti=0;i<=row;i++){// First and last values in every row are 1if(row==i||i==0)arr.add(1);// Other values are sum of values just // above and left of aboveelsearr.add(mat.get(row-1).get(i-1)+mat.get(row-1).get(i));}mat.add(arr);}returnmat;}publicstaticvoidmain(String[]args){intn=5;List<List<Integer>>mat=printPascal(n);for(inti=0;i<mat.size();i++){for(intj=0;j<mat.get(i).size();j++){System.out.print(mat.get(i).get(j)+" ");}System.out.println();}}}
Python
# Python program for Pascal’s Triangle Using Dynamic # Programming in O(n^2) time and O(n^2) extra space defprintPascal(n):# An auxiliary array to store # generated pascal triangle valuesmat=[]# Iterate through every line and # print integer(s) in itforrowinrange(n):# Every line has number of integers # equal to line numberarr=[]foriinrange(row+1):# First and last values in every row are 1ifrow==iori==0:arr.append(1)# Other values are sum of values just # above and left of aboveelse:arr.append(mat[row-1][i-1]+mat[row-1][i])mat.append(arr)returnmatn=5mat=printPascal(n)foriinrange(len(mat)):forjinrange(len(mat[i])):print(mat[i][j],end=" ")print()
C#
// C# program for Pascal’s Triangle Using Dynamic // Programming in O(n^2) time and O(n^2) extra space usingSystem;usingSystem.Collections.Generic;classGfG{staticList<List<int>>printPascal(intn){// An auxiliary array to store // generated pascal triangle valuesList<List<int>>mat=newList<List<int>>();// Iterate through every line and // print integer(s) in itfor(introw=0;row<n;row++){// Every line has number of integers // equal to line numberList<int>arr=newList<int>();for(inti=0;i<=row;i++){// First and last values in every row are 1if(row==i||i==0)arr.Add(1);// Other values are sum of values just // above and left of aboveelsearr.Add(mat[row-1][i-1]+mat[row-1][i]);}mat.Add(arr);}returnmat;}staticvoidMain(){intn=5;List<List<int>>mat=printPascal(n);for(inti=0;i<mat.Count;i++){for(intj=0;j<mat[i].Count;j++){Console.Write(mat[i][j]+" ");}Console.WriteLine();}}}
JavaScript
// JavaScript program for Pascal’s Triangle Using Dynamic // Programming in O(n^2) time and O(n^2) extra space functionprintPascal(n){// An auxiliary array to store // generated pascal triangle valuesconstmat=[];// Iterate through every line and // print integer(s) in itfor(letrow=0;row<n;row++){// Every line has number of integers // equal to line numberconstarr=[];for(leti=0;i<=row;i++){// First and last values in every row are 1if(row===i||i===0)arr.push(1);// Other values are sum of values just // above and left of aboveelsearr.push(mat[row-1][i-1]+mat[row-1][i]);}mat.push(arr);}returnmat;}constn=5;constmat=printPascal(n);for(leti=0;i<mat.length;i++){letline="";for(letj=0;j<mat[i].length;j++){line+=mat[i][j]+" ";}console.log(line);}
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time Complexity - O(n2) Auxiliary Space - O(n2)
Note: This method can be optimized to use O(n) extra space as we need values only from previous row. So we can create an auxiliary array of size n and overwrite values. Following is another method uses only O(1) extra space.
[Expected Approach] Using Binomial Coefficient (Space Optimized)
This method is based on approach using Binomial Coefficient. We know that ith entry in a row (n) in Binomial Coefficient isnCiand all rows start with value 1. The idea is to calculate nCi-1 using nCi . It can be calculated in O(1) time.
nCi = n! / (i! * (n-i)!) - (Eq - 1)
nCi-1 = n! / ((i-1)! * (n-i+1)!) - (Eq - 2)
On solving Eq- 1 further , we get nCi = n! / (n-i)! * i * (i-1)!) - (Eq - 3)
On solving Eq- 2 further , we get nCi-1 = n! / ((n- i + 1) * (n-i)! * (i-1)! ) - (Eq - 4)
Now, divide Eq - 3 by Eq - 4:
nCi = nCi-1 * (n-i+1) / i , So nCi can be calculated from nCi-1in O(1) time
C++
// C++ program for Pascal’s Triangle// in O(n^2) time and O(1) extra space#include<bits/stdc++.h>usingnamespacestd;// function for Pascal's TrianglevoidprintPascal(intn){for(introw=1;row<=n;row++){// nC0 = 1intc=1;for(inti=1;i<=row;i++){// The first value in a row is always 1cout<<c<<" ";c=c*(row-i)/i;}cout<<endl;}}intmain(){intn=5;printPascal(n);return0;}
C
// C program for Pascal’s Triangle#include<stdio.h>// function for Pascal's TrianglevoidprintPascal(intn){for(introw=1;row<=n;row++){// nC0 = 1intc=1;for(inti=1;i<=row;i++){// The first value in a row is always 1printf("%d ",c);c=c*(row-i)/i;}printf("\n");}}intmain(){intn=5;printPascal(n);return0;}
Java
// Java program for Pascal’s Triangle// in O(n^2) time and O(1) extra spaceimportjava.util.*;classGfG{// function for Pascal's TrianglestaticvoidprintPascal(intn){for(introw=1;row<=n;row++){// nC0 = 1intc=1;for(inti=1;i<=row;i++){// The first value in a row is always 1System.out.print(c+" ");c=c*(row-i)/i;}System.out.println();}}publicstaticvoidmain(String[]args){intn=5;printPascal(n);}}
Python
# Python program for Pascal’s Triangle# in O(n^2) time and O(1) extra space# function for Pascal's TriangledefprintPascal(n):forrowinrange(1,n+1):# nC0 = 1c=1foriinrange(1,row+1):# The first value in a row is always 1print(c,end=" ")c=c*(row-i)//iprint()n=5printPascal(n)
C#
// C# program for Pascal’s Triangle// in O(n^2) time and O(1) extra spaceusingSystem;usingSystem.Collections.Generic;classGfG{// function for Pascal's TrianglestaticvoidprintPascal(intn){for(introw=1;row<=n;row++){// nC0 = 1intc=1;for(inti=1;i<=row;i++){// The first value in a row// is always 1Console.Write(c+" ");c=c*(row-i)/i;}Console.WriteLine();}}staticvoidMain(){intn=5;printPascal(n);}}
JavaScript
// JavaScript program for Pascal’s Triangle// in O(n^2) time and O(1) extra spacefunctionprintPascal(n){for(letrow=1;row<=n;row++){// nC0 = 1letc=1;letline="";for(leti=1;i<=row;i++){// The first value in a row is always 1line+=c+" ";c=Math.floor(c*(row-i)/i);}console.log(line);}}constn=5;printPascal(n);
Output
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Time Complexity - O(n2) Auxiliary Space - O(1)
Related articles:
Find just the one element of a pascal's triangle given row number and column number in O(n) time.