fork(1) download
  1.  
  2. #include <vector>
  3. #include <iostream>
  4.  
  5. std::vector<unsigned int> pascal(unsigned int n)
  6. {
  7. // This variable is static, to cache results.
  8. // Not a problem, as long as mathematics do not change between two calls,
  9. // which is unlikely to happen, hopefully.
  10. static std::vector<std::vector<unsigned int> > triangle;
  11.  
  12. if(triangle.size() <= n)
  13. {
  14. // Compute for i = last to n-1
  15. while(triangle.size() != n)
  16. pascal(triangle.size());
  17.  
  18. // Compute for n
  19. if(n == 0)
  20. triangle.push_back(std::vector<unsigned int>(1,1));
  21. else
  22. {
  23. std::vector<unsigned int> result(n + 1, 0);
  24. for(unsigned int k = 0; k <= n; k++)
  25. {
  26. unsigned int l = (k > 0 ? triangle[n - 1][k - 1] : 0);
  27. unsigned int r = (k < n ? triangle[n - 1][k] : 0);
  28. result[k] = l + r;
  29. }
  30. triangle.push_back(result);
  31. }
  32. }
  33.  
  34. // Finish
  35. return triangle[n];
  36. }
  37.  
  38. std::ostream& operator<<(std::ostream& out, const std::vector<unsigned int>& v)
  39. {
  40. for(unsigned int t = 0; t < v.size(); t++)
  41. out << v[t] << " ";
  42. return out;
  43. }
  44.  
  45. int main()
  46. {
  47. for(unsigned int t = 0; t < 6; t++)
  48. std::cout << pascal(t) << "\n";
  49. }
  50.  
  51.  
Success #stdin #stdout 0.02s 2860KB
stdin
Standard input is empty
stdout
1 
1 1 
1 2 1 
1 3 3 1 
1 4 6 4 1 
1 5 10 10 5 1