LeetCode 96: Unique Binary Search Trees
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
Subscribe to see which companies asked this question
// Consists of 1, 2, 3 ,..., the binary search tree built by n, with I as the root node, the left subtree is composed of [1, I-1], and the right subtree is composed of [I + 1, n. // Define f (I) as the number of Unique Binary Search trees that can be generated using [1, I] // If the array is empty, there is only one BST, that is, an empty Tree, f (0) = 1; // If the array has only one element 1, there is only one type of BST, one node, f (1) = 1; // If the array has two elements, 1 and 2, there are two possibilities: f (2) = f (0) * f (1) + f (1) * f (0 ); // If the array has three elements 1, 2, 3, f (3) = f (0) * f (2) + f (1) * f (1) + f (2) * f (0) // The recursive formula f (I) = f (0) * f (I-1) +... + f (k-1) * f (I-k) +... + f (I-1) * f (0) // use one-dimensional dynamic programming to solve class Solution {public: int numTrees (int n) {vector
F (n +); // n + 1 int element, each initialized to 0f [0] = 1; f [1] = 1; for (int I = 2; I <= n; ++ I) {for (int k = 1; k <= I; ++ k) f [I] = f [I] + f [k-1] * f [I-k];} return f [n] ;}};