LeetCode:Unique Binary Search Trees

来源:互联网 发布:淘宝大码女装 编辑:程序博客网 时间:2024/04/30 04:29

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

// Source : https://oj.leetcode.com/problems/unique-binary-search-trees/// Author : Chao Zeng// Date   : 2014-12-18class Solution {public:    int numTrees(int n) {        return combination(2*n,n)/(n + 1);    }    int64_t combination(int num1, int num2){        int64_t ans1 = 1, ans2 = 1;        int i;        for (i = num1; i > num2; i--)            ans1*=i;        for (i = num2; i > 0; i--)            ans2*=i;        return ans1 / ans2;    }};


0 0
原创粉丝点击