LeetCode 96: Unique Binary Search Trees

Source: Internet
Author: User

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] ;}};
 


 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.