Skip to content

Latest commit

 

History

History
34 lines (31 loc) · 782 Bytes

UniqueBinarySearchTrees.md

File metadata and controls

34 lines (31 loc) · 782 Bytes

Unique Binary Search Trees

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

For example, 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

##Solutions

class Solution {
public:
    // set i as the root, then i-1 nodes in left and n-i nodes in right
    int numTrees(int n) {
        int dp[n+1];
        memset(dp, 0, sizeof(dp));
        dp[0] = 1;
        for(int i=1;i<=n;i++){
            for(int j=0;j<i;j++){
                dp[i] += dp[j]*dp[i-j-1];
            }
        }
        return dp[n];
    }
};