96 Unique Binary Search Trees

https://leetcode.com/problems/unique-binary-search-trees/#/description

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

分析和代码

动规

public int numTrees(int n) {
    if(n < 3) {
        return n;
    }
    int[] record = new int[n + 1];
    record[0] = 1;
    record[1] = 1;
    record[2] = 2;
    for(int i = 3; i <= n; i++) {
        for(int j = 0; j < i; j++) {
            record[i] += (record[j] * record[i - 1 - j]);
        }
    }
    return record[n];
}

O(n^2)

results matching ""

    No results matching ""