Explanation
The crucial observation here is that the answer for nodes is the th Catalan number.
Proof
Implementation
Time Complexity:
C++
class Solution {public:long long nCr(int n, int k) {long long res = 1;// since C(n, k) = C(n, n - k)if (k > n - k) { k = n - k; }for (int i = 0; i < k; i++) {res *= (n - i);
Java
class Solution {public int numTrees(int n) { return (int)(nCr(2 * n, n) / (long)(n + 1)); }public long nCr(int n, int k) {long res = 1;// since C(n, k) = C(n, n - k)if (k > n - k) { k = n - k; }for (int i = 0; i < k; i++) {
Python
import mathclass Solution:def numTrees(self, n: int) -> int:res = math.comb(2 * n, n) // (n + 1)return res
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!