【LeetCode】Unique Binary Search Trees

来源:互联网 发布:英语配音软件哪个好 编辑:程序博客网 时间:2024/06/06 02:39

题目描述:

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
解:

只看根节点的左右子树,假设左子树元素数目为i1,右子树为i2,dp表示元素数为i时二叉树的数目,对于i=i1+i2+1,有dp[i]=dp[i1]*dp[i2]。对于给定的n,从第一个元素开始遍历至最后一个元素即可。

代码如下:

class Solution {public:    int numTrees(int n) {if (n == 0)return 0;vector<int> count;count.push_back(1);for (int i = 1; i <= n; i++){int num(0);for (int j = 0; j < i / 2; j++)num += count[j] * count[i - j - 1];num *= 2;if (i % 2 == 1)num += count[(i - 1) / 2] * count[(i - 1) / 2];count.push_back(num);}return count[n];}};


0 0