/*
* ALGORITHM : Dynamic Programming.
* Input size of triangle n.
* Allocate a 2-D array of size nxn.
* Recurrence relation C(n,k) = C(n-1,k-1) + C(n-1,k)
* Use 2-D matrix to store C(n,k) at arr[i][j].
* Time complexity O(n2) and O(n) extra space.
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#define CLR(a) memset(a,0,sizeof a)
using namespace std;
void printSpaces(int sp)
{
int i,j;
printf("\n");
for(i=0; i<sp; i++)
printf(" ");
}
void binomialCoefficient(int n)
{
int i,j;
int arr[n+1][n+1];
CLR(arr);
for(i=0; i<=n;i++)
{
for(j=0;j<= n ;j++)
{
if( j ==0 || i == j)
arr[i][j] = 1;
else
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
}
for(i=0;i<=n;i++)
{
printSpaces(n-i);
for(j=0;j<=i;j++)
printf("%d ",arr[i][j]);
}
}
int main()
{
int n;
while(true)
{
scanf("%d",&n);
if(n <= 0)
break;
binomialCoefficient(n);
}
}
/*
OUTPUT
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
*/
Tuesday, 3 September 2013
Pascal Triangle.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment