[Leetcode] Unique Binary Search Trees

Unique Binary Search Trees 题解

原创文章,拒绝转载

题目来源:https://leetcode.com/problems/unique-binary-search-trees/description/


Description

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

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

Solution


class Solution {
private:
    vector<int> values;
    int getValue(int index) {
        if (values[index] > 0)  // 已经计算过的不重新计算
            return values[index];
        int temp = getValue(index - 1) * 2;  // 初始值先算上位于左右边界的时候的情况
        for (int i = 1; i <= index - 2; i++) {
            temp += getValue(i - 0) * getValue(index - 1 - i); // 左侧数目乘以右侧数目
        }
        values[index] = temp;
        return temp;
    }
public:
    int numTrees(int n) {
        if (n <= 1)
            return 1;
        if (n == 2)
            return 2;
        values = vector<int>(n + 1, 0);
        values[0] = 1;
        values[1] = 1;
        values[2] = 2;
        return getValue(n);
    }
};



解题描述

这道题是要求,给定一个数组长度,求这个长度的数组能构建出多少棵不同的二叉查找树(BST),上面给出来的是我一开始的算法,采用递归的思想比较好理解。不过AC之后还是使用非递归的方式进行了改进,也确实因为结果数据一直是正向逐个增长的,没有乱序变化,因此不必使用递归:


class Solution {
private:
    vector<int> values;
public:
    int numTrees(int n) {
        if (n <= 1)
            return 1;
        if (n == 2)
            return 2;
        values = vector<int>(n + 1, 0);
        values[0] = 1;
        values[1] = 1;
        values[2] = 2;

        int i, j;
        for (i = 3; i <= n; i++) {
            values[i] = values[i - 1] * 2;  // 初始值先算上位于左右边界的时候的情况
            for (j = 1; j <= i - 2; j++) {
                values[i] += values[j] * values[i - 1 - j];  // 左侧数目乘以右侧数目
            }
        }

        return values[n];
    }
};

posted @ 2018-01-22 21:18  言何午  阅读(82)  评论(0编辑  收藏  举报