|
| 1 | +package DynamicProgramming; |
| 2 | + |
| 3 | +/** |
| 4 | + * This file contains an implementation of finding the nth CATALAN NUMBER using dynamic programming |
| 5 | + * Wikipedia: https://en.wikipedia.org/wiki/Catalan_number |
| 6 | + * |
| 7 | + * Time Complexity: O(n^2) |
| 8 | + * Space Complexity: O(n) |
| 9 | + * |
| 10 | + * @author AMRITESH ANAND (https://github.com/amritesh19) |
| 11 | + */ |
| 12 | + |
| 13 | +import java.util.Scanner; |
| 14 | + |
| 15 | +public class CatalanNumber { |
| 16 | + |
| 17 | + /** |
| 18 | + * This method finds the nth Catalan number |
| 19 | + * |
| 20 | + * @param n input n which determines the nth Catalan number |
| 21 | + * n should be less than equal to 50 as 50th Catalan number is 6,533,841,209,031,609,592 |
| 22 | + * for n > 50, BigInteger class should be used instead long |
| 23 | + * |
| 24 | + * @return catalanArray[n] the nth Catalan number |
| 25 | + */ |
| 26 | + static long findNthCatalan(int n){ |
| 27 | + |
| 28 | + // Array to store the results of subproblems i.e Catalan numbers from [1...n-1] |
| 29 | + long catalanArray[] = new long[n + 1]; |
| 30 | + |
| 31 | + // Initialising C₀ = 1 and C₁ = 1 |
| 32 | + catalanArray[0] = 1; |
| 33 | + catalanArray[1] = 1; |
| 34 | + |
| 35 | + /** |
| 36 | + * The Catalan numbers satisfy the recurrence relation |
| 37 | + * C₀=1 and Cn = Σ (Ci * Cn-1-i), i = 0 to n-1 , n > 0 |
| 38 | + */ |
| 39 | + for(int i = 2; i <= n; i++){ |
| 40 | + catalanArray[i] = 0; |
| 41 | + for(int j = 0; j < i; j++){ |
| 42 | + catalanArray[i] += catalanArray[j] * catalanArray[i - j - 1]; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return catalanArray[n]; |
| 47 | + } |
| 48 | + |
| 49 | + // Main method |
| 50 | + public static void main(String[] args) { |
| 51 | + Scanner sc = new Scanner(System.in); |
| 52 | + |
| 53 | + System.out.println("Enter the number n to find nth Catalan number (n <= 50)"); |
| 54 | + int n = sc.nextInt(); |
| 55 | + System.out.println(n + "th Catalan number is " + findNthCatalan(n)); |
| 56 | + |
| 57 | + sc.close(); |
| 58 | + } |
| 59 | +} |
| 60 | + |
0 commit comments