Unique Binary Search Trees

/*
    卡特兰数,只记得递推公式,
    h(n) = h(n-1)*(4*n-2)/(n+1),
    h(n) = C(2*n,n)/(n+1),
    h(n) = C(2*n,n) - C(2*n,n+1);
*/

class Solution {
public:
    int C(int n,int m){
        int ans = 1,temp = m;
        for(int i = n ; i >=n-m+1; i--){
            ans*=i;
            while(temp>1&&ans%temp ==0){
                ans/=temp;temp--;
            }
        }
        return ans;
    }
    int numTrees(int n) {
        return C(2*n,n)/(n+1);
    }
};

 

posted @ 2015-03-14 15:08  SprayT  阅读(82)  评论(0编辑  收藏  举报