LeeCode, leetcodeoj
Question:
GivenN, How many structurally uniqueBST's(Binary search trees) that store values 1...N?
For example,
GivenN= 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
Ideas:
Search rules
1. No node. BST (Binary Search Tree) is one, that is, empty Tree.
2. There is a node and the BST is one, that is, the root node itself.
3. there are two nodes, two BST nodes, one is root, left is empty, right is 2, 2 is root, left is 1, right is empty, it is actually dp [0] * dp [1] + dp [1] * dp [0]
1 2
\/
2 1
4. There are three Nodes
1 1 2 3 3 \ \ / \ / / 3 2 1 3 2 1 / \ / \
2 3 1 2
Dp [3] = dp [0] * dp [2] + dp [1] * dp [1] + dp [2] * dp [0]
package bst;public class UniqueBinarySearchTrees { public int numTrees(int n) { int[] dp = new int[n + 1]; dp[0] = 1; dp[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 0; j < i; ++j) { dp[i] += dp[j] * dp[i - 1 - j]; } } return dp[n]; } public static void main(String[] args) { // TODO Auto-generated method stub UniqueBinarySearchTrees u = new UniqueBinarySearchTrees(); System.out.println(u.numTrees(3)); }}