首页 > 程序开发 > 软件开发 > C++ >

Unique Binary Search Trees

2013-07-11

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...

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

class Solution {
public:
    int numTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n <= 2) return n;
        
        vector<int> f(n+1, 1);
        f[1] = 1;
        f[2] = 2;
        
        int tmp;
        for(int i = 3; i <= n; i++){
            tmp = 0;
           for(int j = 0; j < i; j++){
               tmp += f[j] * f[i-1-j];
           }
           f[i] = tmp;
            
        }
        
        
        return f[n];
    }
};

相关文章
最新文章
热点推荐