|
| 1 | +/** Print all the Catalan numbers from 0 to n, n being the user input. |
| 2 | +
|
| 3 | + * A Catalan number satifies the following two properties: |
| 4 | + * C(0) = C(1) = 1; C(n) = sum(C(i).C(n-i-1)), from i = 0 to n-1 |
| 5 | + * Read more about Catalan numbers here: |
| 6 | + https://en.wikipedia.org/wiki/Catalan_number |
| 7 | + */ |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +using namespace std; |
| 11 | + |
| 12 | +int *cat; // global array to hold catalan numbers |
| 13 | + |
| 14 | +unsigned long int catalan_dp(int n) |
| 15 | +{ |
| 16 | + /** Using the tabulation technique in dynamic programming, |
| 17 | + this function computes the first `n+1` Catalan numbers |
| 18 | +
|
| 19 | + Parameter |
| 20 | + --------- |
| 21 | + n: The number of catalan numbers to be computed. |
| 22 | +
|
| 23 | + Returns |
| 24 | + ------- |
| 25 | + cat[n]: An array containing the first `n+1` Catalan numbers |
| 26 | + */ |
| 27 | + |
| 28 | + // By definition, the first two Catalan numbers are 1 |
| 29 | + cat[0] = cat[1] = 1; |
| 30 | + |
| 31 | + // Compute the remaining numbers from index 2 to index n, using tabulation |
| 32 | + for (int i = 2; i <= n; i++) |
| 33 | + { |
| 34 | + cat[i] = 0; |
| 35 | + for (int j = 0; j < i; j++) |
| 36 | + cat[i] += cat[j] * cat[i-j-1]; // applying the definition here |
| 37 | + } |
| 38 | + |
| 39 | + // Return the result |
| 40 | + return cat[n]; |
| 41 | +} |
| 42 | + |
| 43 | +int main(int argc, char *argv[]) |
| 44 | +{ |
| 45 | + int n; |
| 46 | + cout << "Enter n: "; |
| 47 | + cin >> n; |
| 48 | + |
| 49 | + cat = new int[n+1]; |
| 50 | + |
| 51 | + cout << "Catalan numbers from 0 to " << n << " are:\n"; |
| 52 | + for (int i = 0; i <= n; i++) |
| 53 | + { |
| 54 | + cout << "catalan (" << i << ") = " << catalan_dp(i) << endl; |
| 55 | + // NOTE: Since `cat` is a global array, calling `catalan_dp` |
| 56 | + // repeatedly will not recompute the the values already computed |
| 57 | + // as in case of pre-computed values, the array will simply return them, |
| 58 | + // instead of recomputing them. |
| 59 | + } |
| 60 | + |
| 61 | + return 0; |
| 62 | +} |
| 63 | + |
| 64 | +/** Sample Test Case: |
| 65 | +
|
| 66 | +$ cd "Dynamic Programming" |
| 67 | +$ g++ Catalan-Numbers.cpp |
| 68 | +$ ./a.exe |
| 69 | +
|
| 70 | +Enter n: 5 |
| 71 | +Catalan numbers from 0 to 5 are: |
| 72 | +catalan (0) = 1 |
| 73 | +catalan (1) = 1 |
| 74 | +catalan (2) = 2 |
| 75 | +catalan (3) = 5 |
| 76 | +catalan (4) = 14 |
| 77 | +catalan (5) = 42 |
| 78 | +
|
| 79 | +*/ |
0 commit comments