96. Unique Binary Search Trees

来源:互联网 发布:西门子plc编程入门教程 编辑:程序博客网 时间:2024/05/09 00:03

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

题目是求N个结点的二分查找树有多少种不同的。

它的个数为分别以每个数i为根节点时的数量,全部加起来。

而二分查找树小于根节点的在左边,大于根节点的一定在右边,所以两者相乘即为结果。

class Solution {  public:      int numTrees(int n) {          int *num=new int[n+1];        memset(num, 0, sizeof(int) * (n + 1));        num[0]=1;        for(int i=1; i<=n; i++){             for(int j=1; j<=i; j++)                  num[i]+=num[j-1]*num[i-j];          }          return num[n];      }  };  



0 0
原创粉丝点击