LeetCode 96:Unique Binary Search Trees

Posted llguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 96: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

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];
	}
};

技术分享图片

以上是关于LeetCode 96:Unique Binary Search Trees的主要内容,如果未能解决你的问题,请参考以下文章

Java [Leetcode 96]Unique Binary Search Trees

[动态规划] leetcode 96 Unique Binary Search Trees

Leetcode 96. Unique Binary Search Trees

Leetcode 96. Unique Binary Search Trees

LeetCode 96:Unique Binary Search Trees

leetcode96 Unique Binary Search Trees