[LeetCode-interview algorithm classic-Java implementation] [096-Unique Binary Search Trees (Unique Binary Search Tree)], leetcode -- java
[096-Unique Binary Search Trees (Unique Binary Search Tree )][LeetCode-interview algorithm classic-Java implementation] [directory indexes for all questions]Original question
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
Theme
Given a binary search tree with n nodes, calculate the total number of different types of binary search trees.
Solutions
Recurrence Formula
F (k) * f (n-1-k): f (k) indicates that the Left subtree of the root node has k nodes, its shape is f (k), f (n-1-k) indicates that the right subtree has n-1-k nodes
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 class Solution {public int numTrees (int n) {if (n <= 0) {return 0;} else if (n = 1) {return 1 ;} int [] result = new int [n + 1]; result [0] = 0; result [1] = 1; // evaluate f (2 )... f (n) for (int I = 2; I <= n; I ++) {// evaluate f (I) result [I] = 2 * result [I-1]; for (int j = 1; j <= I-1; j ++) {result [I] + = result [j] * result [I-1-j] ;}} return result [n] ;}}
Evaluation Result
Click the image. If you do not release the image, drag it to a position. After the image is released, you can view the complete image in the new window.
Note Please refer to the following link for more information: http://blog.csdn.net/derrantcm/article/details/47333321]
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.