您的位置:首页 > 编程语言 > C语言/C++

leetcode_c++:树: Unique Binary Search Trees(096)

2016-08-23 18:20 513 查看
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

//求个数

算法

o(n^2)

dp[i]=dp[k]*dp[i-k+1] {0<=k<=i-1}

https://github.com/illuz/leetcode/tree/master/solutions/095.Unique_Binary_Search_Trees

class Solution {
public:
int numTrees(int n) {
vector<int> dp(n+1);  //n+1个元素,元素是0
dp[1]=dp[0]=1;
for(int i=2;i<=n;i++)
for(int k=0;k<i;k++)
dp[i]+=dp[k]*dp[i-k-1];
return dp
;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: