[leetcode] Unique Binary Search Trees


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
Show Tags

Tree Dynamic Programming

感觉是一道数学题,找到递推公式,然后一切迎刃而解。

对于BST,每个节点都可以作为root节点。只是root节点的左节点必须都比root小,右节点都比root大。

所以对于N,选取1~N每个数字分别作为一次root节点,则F(N) = sum(F(K) * F(N-1-K)), (0<= k <= n – 1)

此时应用动态规划,避免用递归,因为会产生大量的重复计算。

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

Untitled1

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.