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
思路:
我们设置dp[n]是存储n个连续值的BST的数量
得到dp[n]:
设1为根节点,左子树有0个子节点,右子树有n - 1个子节点,bst个数为dp[0] * dp[n - 1](设dp[0] = 1);
设2为根节点,左子树有1个子树,右子树有n - 2个子树,bst个数为dp[1] * dp[n - 2];
一般情况下,我们将k设为根节点,所以左边的子树有k - 1个子节点,右边的子树有n - k个子节点,bst的个数是dp[k - 1] * dp[n - k];
dp[n] = d[0] * dp[n - 1] +…+ dp[k - 1] * dp[n - k] +…+ dp[n - 1] * dp[0];
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 k = 1; k <= i; ++k) { dp[i] += dp[k - 1] * dp[i - k]; } } return dp[n]; } };