"Leetcode-Interview algorithm classic-java implementation" "096-unique binary search Trees (the only binary searching tree)"

Source: Internet
Author: User

"096-unique binary search Trees (the only binary searching tree)" "leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index" Original Question

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

Main Topic

Given a two-fork search tree of n nodes, find out how many different types of two-fork search trees are in total.

Thinking of solving problems

Recursive formulas
F (k) *f (N-1-k): F (k) indicates that there are k nodes in the left subtree of the root node, the shape of which is f (k), and F (n-1-k) indicates that the right subtree has a n-1-k node.
F (n) = 2*f (n-1) + f (1) *f (n-2) + f (2) *f (n-3) + f (3) *f (n-4) + ... +f (n-2) *f (1)

Code Implementation

Algorithm implementation class

 Public classSolution { Public int numtrees(intN) {if(N <=0) {return 0; }Else if(n = =1) {return 1; }int[] result =New int[n +1]; result[0] =0; result[1] =1;//Ask F (2) ... f (n)         for(inti =2; I <= N; i++) {//Ask F (i)Result[i] =2* Result[i-1]; for(intj =1; J <= I-1; J + +) {Result[i] + = result[j]*result[i-1-J]; }        }returnResult[n]; }}
Evaluation Results

  Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.

Special Instructions Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47333321"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode-Interview algorithm classic-java implementation" "096-unique binary search Trees (the only binary searching tree)"

Related Article

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.