首页 > 代码库 > Unique Binary Search Trees

Unique Binary Search Trees

 这里需要总结规律:

f(0)=f(1)=1;

f(2)=f(0)*f(1) + f(1)*f(0)

f(3)=f(0)*f(2) + f(1)*f(1) + f(2)*f(0)

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

 

Unique Binary Search Trees