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

解法
二分查找树的定义是,左子树节点均小于root,右子树节点均大于root
所以采用递归的思想选定一个点为root,cnt = 左子树情况数 * 右子树情况数

查表优化

class Solution {
private:
    vector<int> tb;
public:
    int numTrees(int n) {
        tb.resize(n + 1, 0);
        tb[0] = 1;
        tb[1] = 1;
        tb[2] = 2;
        return dfs(n);
    }
    
    int dfs(int x){
        if(tb[x]) return tb[x];
        int cnt = 0;
        for(int i = 1; i <= x; i++){
            cnt += dfs(i - 1) * dfs(x - i);
        }
        tb[x] = cnt;
        return cnt;
    }
};

动态规划

class Solution {
private:
    vector<int> tb;
public:
    int numTrees(int n) {
        tb.resize(n + 1, 0);
        return dp(n);
    }
    
    int dp(int n){
       tb[0] = 1;
       tb[1] = 1;
       tb[2] = 2;
       for(int i = 3; i <= n; i++){
           for(int j = 1; j <= n; j++){
               tb[i] += tb[j - 1] * tb[i - j];
           }
       }
       return tb[n];
    }
}; 

你可能感兴趣的:(96. Unique Binary Search Trees)