Let's make this one less mysterious. For 96. Unique Binary Search Trees, the solution in this repository is mainly a binary search solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: binary search, two pointers.
The notes already sitting in the source point us in the right direction:
- https://ithelp.ithome.com.tw/articles/10216235
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are numTrees, T.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//https://ithelp.ithome.com.tw/articles/10216235
02//Runtime: 0 ms, faster than 100.00% of C++ online submissions for Unique Binary Search Trees.
03//Memory Usage: 6.1 MB, less than 100.00% of C++ online submissions for Unique Binary Search Trees.
04class Solution {
05public:
06 int numTrees(int n) {
07 vector<int> T(n+1, 0);
08
09 T[0] = T[1] = 1;
10
11 for(int r = 2; r <= n; r++){
12 for(int mid = 1; mid <= r; mid++){
13 /*
14 if the tree is rooted at mid,
15 the left and right subtree would be:
16 [1...mid-1] and [mid+1...r]
17 since the right subtree's max size is r-1,
18 so mid starts from 1,
19 and since the left subtree's max size is r-1,
20 so mid ends at r
21 */
22 T[r] += T[mid-1] * T[r-mid];
23 }
24 // cout << T[r] << " ";
25 }
26 // cout << endl;
27
28 return T[n];
29 }
30};
Cost