[LeetCode] Unique Binary Search Trees

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

把上例的顺序改一下,就可以看出规律了。
 1                1                      2                       3             3
    \                 \                 /      \                  /              / 
      3               2              1       3               2             1
    /                   \                                       /                  \
 2                       3                                   1                    2

比如,以1为根的树有几个,完全取决于有二个元素的子树有几种。同理,2为根的子树取决于一个元素的子树有几个。以3为根的情况,则与1相同。
the number of binary search tree equals the left child tree * right child tree

If there are three element in the array, there are three situations

root is 1, left has 0 , right has 2

root is 2, left has 1, right has 1

root is 3, left has 2, right has 0


定义Count[i] 为以[0,i]能产生的Unique Binary Tree的数目,

如果数组为空,毫无疑问,只有一种BST,即空树,
Count[0] =1

如果数组仅有一个元素{1},只有一种BST,单个节点
Count[1] = 1

如果数组有两个元素{1,2}, 那么有如下两种可能
1                       2
  \                    /
    2                1
Count[2] = Count[0] * Count[1]   (1为根的情况)
                  + Count[1] * Count[0]  (2为根的情况。

再看一遍三个元素的数组,可以发现BST的取值方式如下:
Count[3] = Count[0]*Count[2]  (1为根的情况)
               + Count[1]*Count[1]  (2为根的情况)
               + Count[2]*Count[0]  (3为根的情况)

所以,由此观察,可以得出Count的递推公式为
Count[i] = ∑ Count[0...k] * [ k+1....i-1]     0<=k<i
问题至此划归为一维动态规划。

java

public int numTrees(int n) {
        if(n<=1) return n;
        int [] count = new int[n+1];
        count[0] = 1;
        count[1] = 1;
        for(int i=2;i<=n;i++){
            count[i]=0;
            for(int j=0;j<i;j++){
                count[i]+=count[j]*count[i-j-1];
            }
        }
        return count[n];
    }

c++

int numTrees(int n) {
    vector<int> count1(n+1,0);
    count1[0] = 1;
    count1[1] = 1;
    for(int i=2;i<=n;i++){
        for(int j=0; j<i;j++){
            count1[i] += count1[j]*count1[i-j-1]; 
        }
    }
    return count1[n];
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值