Unique Binary Search Trees

LeetCode Q 96 - Unique Binary Search Trees

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:
Input: 3 ; Output: 5

Solution : DP

Code:

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 - j - 1];
	}
	return dp[n];
}

   Reprint policy


《Unique Binary Search Trees》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC