Skip to content

Instantly share code, notes, and snippets.

@0001vrn
Created July 18, 2017 12:48
Show Gist options
  • Select an option

  • Save 0001vrn/a0c59016b97ca6ffb45879cf6c7f00af to your computer and use it in GitHub Desktop.

Select an option

Save 0001vrn/a0c59016b97ca6ffb45879cf6c7f00af to your computer and use it in GitHub Desktop.
Pascal’s triangle is a triangular array of the binomial coefficients. Write a function that takes an integer value n as input and prints first n lines of the Pascal’s triangle. Following are the first 6 rows of Pascal’s Triangle.
/*
Pascal’s triangle is a triangular array of the binomial coefficients.
Write a function that takes an integer value n as input and prints
first n lines of the Pascal’s triangle. Following are the first 6
rows of Pascal’s Triangle.
*/
#include <iostream>
using namespace std;
int binomialCoefficient(int, int);
void printPascal(int n){
for(int line=0;line<n;line++)
{
for(int i=0;i<=line;i++)
printf("%d ",binomialCoefficient(line,i));
printf("\n");
}
}
/*
Time Complexity : O(n^3)
Space Complexity : O(1)
*/
int binomialCoefficient(int n,int k)
{
int res = 1;
if(k > n-k)
k = n-k;
for(int i=0;i<k;i++)
{
res*=(n-i);
res/=(i+1);
}
return res;
}
/*
Time Complexity : O(k)
Space Complexity : O(1)
*/
void printPascal2(int n)
{
int arr[n][n];
for(int line=0;line<n;line++)
{
for(int i=0;i<=line;i++)
{
if(i==0||line==i)
arr[line][i]=1;
else
arr[line][i] = arr[line-1][i-1]+arr[line-1][i];
printf("%d ",arr[line][i]);
}
printf("\n");
}
}
/*
Time Complexity : O(n^2)
Space Complexity : O(n^2)
*/
// A O(n^2) time and O(1) extra space function for Pascal's Triangle
void printPascal3(int n)
{
for (int line = 1; line <= n; line++)
{
int C = 1; // used to represent C(line, i)
for (int i = 1; i <= line; i++)
{
printf("%d ", C); // The first value in a line is always 1
C = C * (line - i) / i;
}
printf("\n");
}
}
/*
Time Complexity : O(n^2)
Space Complexity : O(1)
*/
int main() {
// your code goes here
printPascal3(5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment