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
思路:
采用递归,注意 左子树为空、右子树为空(此时可以采用加法: 一个为0,一个非0)及 左右子树都只有一个节点(此时只有一种情况,1 * 1 = 1,所以可以并入乘法里)的情况。
class Solution {
public:
int numTrees(int n) {
if (n == 0 || n == 1 || n == 2)
return n;
int num = 0;
for (int i = 0; i < n; i++) {
int a = numTrees(i), b = numTrees(n - i - 1);
if (a == 0 || b == 0)
num += a + b;
else
num += a * b;
}
return num;
}
};