LeetCode | Unique Binary Search Trees
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
//要求是binary search tree,故要满足左<中<右的有序状态,即中序遍历有序 //难点在找状态的递推关系,思路:取i作为root,那么要保证root节点有序,root.left就只能用[1,i-1]来构造,root.right就只能用[i+1,n]来构造,则对i来说总的可能数量就是num_left * num_right = states[i-1]*states[n-(i+1)+1]。而在[1,n]中每个数都可以作为root来尝试构造,故要求从1到n的累计和。 //递推公式:states[1]=1, dp[i] = sum{ dp[0]*dp[i-1], dp[1]*dp[i-2], dp[2]*dp[i-3],..., dp[i-1]*dp[0] }
public class Solution { public int numTrees(int n) { if(n == 0) return 1; if(n == 1) return 1; //状态变量数组,states[i]代表n=i时具有的BST个数 int[] states = new int[n+1]; //包含n=0,共n+1项 states[0] = 1; states[1] = 1; //状态转移公式:(卡塔兰数的递推关系) //dp[i] = sum{ dp[0]*dp[i-1], dp[1]*dp[i-2], dp[2]*dp[i-3],..., dp[i-1]*dp[0] } for(int i=2; i<=n; i++){ int sum = 0; for(int j=0; j<i; j++){ int temp = states[j] * states[i-1-j]; sum += temp; } states[i] = sum; } return states[n]; } }