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

来源:互联网 发布:为什么登录淘宝就闪退 编辑:程序博客网 时间:2024/05/14 09:07

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[n];    }};
0 0
原创粉丝点击