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
The question is: given a number n, the output of how many kinds of binary search trees can be represented in the form.
Problem-solving idea: because it is to give a number n, to ask for all of its representation quantity, you can simply consider, set f[n] for n corresponding total.
Assuming n=4, then the number of the left and right subtree is corresponding to 1, the form of f[0]*f[3],f[0] and f[3] respectively;
Take 2 as root, form common f[1]*f[2] species;
Take 3 as root, form common f[2]*f[1] species;
Take 4 as root, form common f[3]*f[0] species;
So f[4]=f[0]*f[3]+f[1]*f[2]+f[2]*f[1]+f[3]*f[0], this can write code, from small to large launch.
Public intNumtrees (intN) {int[] DP =New int[n + 1]; Arrays.fill (DP,0); dp[0] = 1; for(inti = 1; I <= N; i++) { for(intj = 1; J <= I; J + +) {Dp[i]+ = dp[j-1] * dp[i-J]; } } returnDp[n]; }
Unique Binary Search Trees--leetcode