题目:
Given n, how many structurally unique BST's (binary search trees) that store values 1...n? (Medium)
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
分析:
考察用n个节点组成的BST的个数与1...n-1之间的关系。
枚举每一个节点作为其根节点即可得到,dp[n] = dp[0] * dp[n - 1] + dp[1] * dp[n - 2] + ... + dp[n - 1] * dp[0];
代码:
1 class Solution { 2 public: 3 int numTrees(int n) { 4 int dp[n + 1] = {0}; 5 dp[0] = 1; 6 dp[1] = 1; 7 for (int i = 2; i <= n; ++i) { 8 for (int j = 0; j < i; ++j) { 9 dp[i] += (dp[j] * dp[i - 1 - j]); 10 } 11 } 12 return dp[n]; 13 } 14 };