LeetCode 96: Unique Binary Search Tree

来源:互联网 发布:淘宝优品乐购 编辑:程序博客网 时间:2024/06/05 05:09

Difficulty: 3

Frequency: 1


Problem:

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

Solution:

class Solution {public:    vector <int> unique;    Solution()    {        unique.push_back(1);        unique.push_back(1);    }    int numTrees(int n) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (n<unique.size())            return unique[n];                unique.resize(n+1, -1);        int i_method = 0;        for (int i = 1; i<=n; i++)        {            if (unique[i-1]==-1)                unique[i-1] = numTrees(i-1);                            if (unique[n-i]==-1)                unique[n-i] = numTrees(n-i);                            i_method += (unique[i-1]*unique[n-i]);        }        unique[n] = i_method;        return unique[n];    }};


Notes:

DP.