题目:
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
解析:
这题没想出来,问题的本质是动态规划,但在动态规划上还有一层维度
函数f(n),返回值为n个节点下二叉树共有多少个
0个节点:有1种情况,即空树 f(0)=1
1个节点:有1种情况 f(1)=1
2个节点:有2种情况
左0右1:f(0) * f(1) = 1
左1右0:f(1) * f(0) = 1
f(2) = 1+1 = 2
3个节点:有3种情况
左0右2:f(0) * f(2) = 2
左1右1:f(1) * f(1) = 1
左2右0:f(2) * f(0) = 2
f(3) = 1+1+2 = 5
n个节点:共有n种情况
左0右n-1:
……
左n-1右0:
每一步都依赖于上一步的解决,只不过在处理前还要看有多少种情况
1 class Solution { 2 public: 3 int numTrees(int n) { 4 vector<int> f(n + 1, 0); 5 f[0] = 1; 6 f[1] = 1; 7 for (int i = 2; i <= n; ++i) { 8 for (int k = 1; k <= i; ++k) 9 f[i] += f[k-1] * f[i - k]; 10 } 11 return f[n]; 12 } 13 };