Unique Binary Search Trees
Q:
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
A:
想象成一个包含n个元素的有序数组,可以组合成的中序二叉排序树的数量,对于A[n],从第1个元素到第n个元素,假设以其中第i个元素为树根,则前i-1个元素必定组成其左子树,
后j-i个元素组成其右子树,左子树的可能个数为A[i - 1],右子树的可能个数为A[j - i],所以以第i个元素为根时的可能性有A[i - 1]*A[j - i]种,dp公式出来了。
要注意A[i - 1]或A[j - i]为0的情况,这种情况要单独提取出来。
class Solution { public: int numTrees(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if (n < 0) return 0; vector<int> num_trees; num_trees.resize(n + 1); num_trees[0] = 0; num_trees[1] = 1; for (int i = 2; i <= n; ++i) { for (int j = 1; j <= i; ++j) { if (!num_trees[j - 1] || !num_trees[i - j]) { num_trees[i] += num_trees[j - 1] + num_trees[i - j]; } else { num_trees[i] += num_trees[j - 1] * num_trees[i - j]; } } } return num_trees.back(); } };
Passion, patience, perseverance, keep it and move on.

浙公网安备 33010602011771号