LeetCode: 96. Unique Binary Search Trees

题目描述

Given n, how many structurally unique BST’s (binary search trees) that store values 1 … n?

Example:

Input: 3
Output: 5
Explanation:
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

解题思路 —— 记忆搜索,动态规划

从理论上讲,所有的动态规划都可以转化为记忆搜索。反之亦然。
用这一道题抛砖引玉。
求 BST 的种数。可以依次选择某个数字当根节点,然后其左/右的数字作为其子树,做同样的操作,即可得到 BST, 统计其种数即可。

AC 代码

记忆化搜索

class Solution {
public:
    int numTrees(int n) {
        static vector<int> record; // 记录
        if(record.size() > n)
        {
            return record[n];
        }
        if(n == 0)
        {
            record.push_back(1);
            return 1;
        }

        int ans = 0;
        // 遍历根节点
        for(int i = 1; i <= n; ++i)
        {
            ans += (numTrees(i-1) * numTrees(n-i));
        }

        record.push_back(ans);
        return ans;
    }
};

动态规划

class Solution {
public:
    int numTrees(int n) {
        vector<int> dp; // dp[i] 表示 i 个不同数字构成的 BST 种数
        dp.push_back(1);
        for(size_t i = 1; i <= n; ++i){
            int tmp = 0;
            for(size_t j = 0; j < i; ++j){
                tmp += dp[j] * dp[i-j-1];
            }
            dp.push_back(tmp);
        }
        return dp[n];
    }
};