一.題目
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
二.解題技巧
三.實現代碼
#include <unordered_map>
using std::unordered_map;
class Solution
{
private:
unordered_map<int, int> PreResult;
public:
int numTrees(int n)
{
if (n == 0)
{
PreResult[0] = 1;
return 1;
}
if (n == 1)
{
PreResult[1] = 1;
return 1;
}
if (PreResult.find(n) != PreResult.end())
{
return PreResult[n];
}
int Result = 0;
for (int HeadIndex = 1; HeadIndex <= n; HeadIndex++)
{
int LeftChildResult = numTrees(HeadIndex - 1);
int RightChildResult = numTrees(n - HeadIndex);
Result += LeftChildResult * RightChildResult;
}
PreResult[n] = Result;
return Result;
}
};