96. Unique Binary Search Trees

Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?

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

tag: DP

class Solution {
    public int numTrees(int n) {
        int[] dp = new int[n + 1];
        dp[0] = 1;
        dp[1] = 1;

        for (int size = 2; size <= n; size++){
            for (int root = 1; root <= size; root++){
                dp[size] += dp[root - 1] * dp[size - root];
            }
        }

        return dp[n];
    }
}

results for ""

    No results matching ""