Problem Description:
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
Basic ideas:
Consider the number of methods corresponding to the left and right subtree, then multiply the method number of left and right subtree (separate processing of the number of subtree nodes is 0). You can recursively find the number of subtree, or you can use an array to record the number of methods of a subtree of known n nodes.
Code:
int numtrees (int n) { //c++ if (n = = 1) return 1; if (n = = 2) return 2; Vector<int> record (n+1,0); Record[0] = 0; RECORD[1] = 1; RECORD[2] = 2; for (int i = 3; I <= n; i++) { int sum = 0; int k; Left nodes for (k = 0; k < i; k++) { int temp; if (k = = 0) temp = record[i-k-1]; else if (i-k-1 = = 0) temp = record[k]; else temp = record[k]*record[i-k-1]; sum + = temp; } Record[i] = sum; } return record[n]; }
[Leetcode] Unique Binary Search Trees