find the nth catalan number in php

The nth Catalan number can be found using recursion or dynamic programming. Here's one way to find it using recursion:

main.php
function catalan($n) {
   if ($n <= 1) {
      return 1;
   }
   $res = 0;
   for ($i=0; $i<$n; $i++) {
      $res += catalan($i)*catalan($n-$i-1);
   }
   return $res;
}

$n = 5;
echo "The " . $n . "th Catalan number is " . catalan($n);
238 chars
14 lines

This implementation has a time complexity of O(4^n).

To reduce the time complexity, we can use dynamic programming with memoization. Here's an implementation using memoization:

main.php
function catalan_dp($n, &$dp) {
   if ($n <= 1) {
      return 1;
   }
   if (isset($dp[$n])) {
      return $dp[$n];
   }
   $res = 0;
   for ($i=0; $i<$n; $i++) {
      $res += catalan_dp($i, $dp)*catalan_dp($n-$i-1, $dp);
   }
   $dp[$n] = $res;
   return $res;
}

$n = 5;
$dp = array();
echo "The " . $n . "th Catalan number is " . catalan_dp($n, $dp);
357 chars
19 lines

This implementation has a time complexity of O(n^2) and a space complexity of O(n).

gistlibby LogSnag