Advertisement
sleepy_coder

Binomial Coefficient

Dec 21st, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. #define     memo(a,b)          memset(a,b,sizeof(a));
  2. #define     foab(i, a, b)      for(__typeof(b) i=(a); i<=(b); i++)
  3. #define     foba(i, a, b)      for(__typeof(b) i=(b); i>=(a); i--)
  4.  
  5.  
  6. int binomialCoefficient(int n, int k){
  7.     //Running Time : O(n.k)
  8.     //Memory : O(k)
  9.     //for the shake of O(k) auxiliary space....
  10.     int c[k+1];
  11.     memo(c, 0)//memset
  12.     //nC0 is 1...so (K = 0) => (nCk = 1) [that implies actually]
  13.     c[0] = 1;
  14.     foab(i, 1, n){
  15.         //compute next row of Pascal's triangle using the previous row
  16.         foba(j, 1, (int)min(i, k)){
  17.             //cout<<c[j-1]<<" "<<c[j]<<endl;
  18.             c[j] = c[j-1] + c[j];//iCj = i-1Cj-1 + i-1Cj....the recurrance we use forever
  19.             //cout<<"  "<<c[j]<<endl;
  20.         }
  21.  
  22.         //cout<<"Pascal's "<<i<<" no Row: "<<endl;
  23.         //foab(j, 0, (int)min(i, k))cout<<c[j]<<" ";
  24.         //cout<<endl;
  25.     }
  26.  
  27.  
  28.     return c[k];
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement