96. Unique Binary Search Trees
Problem statement:
Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
For example,
Given n = 3, there are total of 5 unique BST's.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
Solution:
The problem wants the number of unique BST tree. DP will solve it.
dp[i] means how many bst trees it can build if n == i. The size of dp array is n + 1.
The initial status is dp[0] = 1. There is only one solution when n = 0.
If there are i tree nodes, i - 1 nodes in total for left and right tree. We enumerate all possible solutions from 0 to i - 1, and return dp[n]
The value of dp[n] = dp[j] * dp[n - 1 -j] (0 <= j < n),
j: means how many nodes in left, n - 1 - j: how many nodes in right tree
class Solution { public: int numTrees(int n) { vector<int> dp(n + 1, 0); dp[0] = 1; for(int i = 1; i <= n; i++){ for(int j = 0; j < i; j++){ // if there are j nodes in left tree. // the number of nodes in right tree is i - 1 - j dp[i] += dp[i - 1 - j] * dp[j]; } } return dp[n]; } };