当前位置:编程学习 > C/C++ >>

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

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];
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,