Leetcode (+): Unique Binary Search Trees

Source: Internet
Author: User

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

For example,
Given N = 3, there is a total of 5 unique BST ' s.

 1 3 3 2 1 \///\ 3 2 1 1 3 2//\ 2 1 2 3 
1) The total number of structures is not related to the n ordered number stored, that is, the storage is three-way or 5, 6, 9 results are the same; 2) n=0\1, the result is 1;n ordered number, whichever is the root node, the value to the left of the left dial hand tree, the right is the right subtree, in this case, The total number of possible structures is: Left dial hand number of tree structures * Number of right sub-trees, so the original problem is broken down into two sub-problems, 3) to take N ordered number as the root node of the structure of the problem, you can get the solution of the original problem, but it should be noted, such as: 1, 2, 3 take 1 or 3 as the root node, the structure number is the same, That is, it has symmetry, so also consider the parity, 4) can be decomposed into the same sub-problem, you can use recursion, the program uses a cyclic method. */int numtrees (int n) {vector<int> store;store.push_back (1); Store.push_back (1); for (int i=2;i<=n;++i) {int tmp=0;for (int j=0;j<i/2;++j) {tmp+=2*store[i-1-j]*store[j];} if (i%2) tmp+=store[i/2]*store[i/2];store.push_back (TMP);} return store[n];}




Leetcode (+): Unique Binary Search Trees

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.