Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Input: n = 3
Output: [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Input: n = 1
Output: [[1]]
1 <= n <= 8The problem requires generating all unique binary search trees (BSTs) that store values 1 to n. The strategy hinges on picking each number as a root and recursively constructing all possible left and right subtrees.
The problem can be divided as follows:
i from 1 to n to serve as the root.i-1.i+1 to n.Instead of recalculating solutions for the same subproblems multiple times, we can use a dynamic programming strategy to store results of previously solved problems in a memoization form. This helps reduce redundant computations but is more complex to set up and typically provides similar time complexity benefits for this specific problem.