96. Unique Binary Search Trees

Description

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.

Solution

DP, time O(n), space O(n)

最开始采用递归思路时,很容易就能发现,对于相同的节点数目,所求结果是相同的,这样会在递归时形成大量的重复计算,于是改用DP来做就更加合理了。

class Solution {
    public int numTrees(int n) {
        if (n < 1) {
            return 0;
        }
        
        int[] count = new int[n + 1];
        count[0] = 1;

        for (int i = 1; i <= n; ++i) {
            for (int j = 0; j < i; ++j) {
                // left tree nodes count is [0, i - 1]
                count[i] += count[j] * count[i - j - 1];
            }       
        }
        
        return count[n];
    }
}

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