96. Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n?

Example:

Input: 3
Output: 5
Explanation:
Given n = 3, there are a total of 5 unique BST's:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Constraints:

  • 1 <= n <= 19

class Solution {
public:
    unordered_map<int,int> memo;
    int numTrees(int n) {
        return getUnique(n); 
    }
    int getUnique(int n){
        if(n == 0) return 1;
        if(n <= 2) return n;
        if(memo.count(n)) return memo[n];
        int ans = 0;
        for(int i=1;i<=n;++i){
            ans += getUnique(i-1)*getUnique(n-i);
        }
        memo[n] = ans;
        return ans;
    }
};

simple DFS + memo.

pick one as the root, then count left tree and right tree.

Last updated

Was this helpful?