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.
Problem Solving Ideas:
Binary search tree, just come up to start, but carefully think can find the law: I as the root node, I left subtree is less than I, a total of Numtrees (i-1) species, I right subtree is greater than I, a total of numtrees (n-i) of the situation, multiplication is the root node i is the case, And then loop in turn, can be solved by recursion. Of course, the more efficient way is to replace recursion with DP, Java implementation is as follows:
public int numtrees (int n) { if (n <= 0) return 0;int[] dp = new Int[n + 1];dp [0] = 1;for (int i = 1; i < Dp.leng Th i++) for (int k = 0; k <= i-1; k++) dp[i] + = dp[k] * dp[i-k-1];return dp[n]; }
Java for Leetcode 096 Unique Binary Search Trees