Pascal Triangle

Variation 1

Given row number r and column number c. Print

element at position (r, c) in Pascal’s triangle.

We have an easier formula to find out the element i.e. r-1Cc-1.

so for row and col

n = row-1

r = col-1

ncr = n!/r!*(n-r)! =

Code

int pascalValue(int row, int col){
int n = row-1;
int r = col-1;
long long res = 1;
for(int i=0;i<r;i++){
res = res*(n-i);
res= res/(i+1);
}
return res;
}

Variation 2

Given the row number n. Print the n-th row of Pascal’s triangle.

Naive

We can use above method to calculate all element of nth row by calling above function n times as nth row will have n no of column

T(C) =O(n*n);

Optimal