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
Subscribe to see which companies asked this question
//由1,2,3,...,n构建的二叉查找树,以i为根节点,左子树由[1,i-1]构成。其右子树由[i+1,n]构成。 //定义f(i)为以[1,i]能产生的Unique Binary Search Tree的数目 //若数组为空,则仅仅有一种BST,即空树。f(0)=1; //若数组仅有一个元素1,则仅仅有一种BST,单个节点,f(1)=1; //若数组有两个元素1。2,则有两种可能,f(2)=f(0)*f(1)+f(1)*f(0); //若数组有三个元素1,2,3,则有f(3)=f(0)*f(2)+f(1)*f(1)+f(2)*f(0) //由此能够得到递推公式:f(i)=f(0)*f(i-1)+...+f(k-1)*f(i-k)+...+f(i-1)*f(0) //利用一维动态规划来求解 class Solution { public: int numTrees(int n) { vector<int> f(n+1,0); //n+1个int型元素。每一个都初始化为0 f[0] = 1; f[1] = 1; for (int i = 2; i <= n; ++i){ for (int k = 1; k <= i; ++k) f[i] = f[i] + f[k - 1] * f[i - k]; } return f[n]; } };