1. 程式人生 > >LeetCode 96:Unique Binary Search Trees

LeetCode 96:Unique Binary Search Trees

col courier pan values http truct pos leet fonts

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