I am applying the formula
Cn = (2*(2*n - 1) / (n+1) ) * Cn-1
so is this corect or …?
The answer is not coming correct
import java.util.; public class Main { public static long helper(long n){ if(n == 0){ return 1; } long first = 2(2*n - 1); long second = n + 1; return (first/second)*helper(n-1); } public static void main(String args[]) { Scanner s = new Scanner(System.in); long n = s.nextInt(); System.out.println(helper(n)); } }
the formula for nth catalyn number is
thus your code would be :-
class CatalnNumber {
// A recursive function to find nth catalan number
int catalan(int n) {
int res = 0;
// Base case
if (n <= 1) {
return 1;
}
for (int i = 0; i < n; i++) {
res += catalan(i) * catalan(n - i - 1);
}
return res;
}
public static void main(String[] args) {
CatalnNumber cn = new CatalnNumber();
for (int i = 0; i < 10; i++) {
System.out.print(cn.catalan(i) + " ");
}
}
}
you can optimize it using dp