Given an integer n, count the total number of unique BSTs that can be made using values from 1 to n.
Building upon understanding of Number of unique BST with N keys (Memoization). Pay attention to the cache. Tabulation essentially reconstructs the cache.
Start with the foundation – the base cases, which are the simplest solutions. Then, layer by layer, use the results of the previous layers to calculate the solutions for the next level. This way, we systematically build up the entire solution, avoiding redundant calculations and ensuring efficiency. It is like building a pyramid.
The underlying calculation logic remains fundamentally identical to the original recursive approach, albeit executed in reverse order.
def C(n): cache = [0 for _ in range(n + 1)] cache[0] = cache[1] = 1 for i in range(2, n + 1): result = 0 for j in range(i): result += cache[j] * cache[i - 1 - j] cache[i] = result return cache[n] n = 5 n = 5 print(C(n))
function C(n) { const cache = new Array(n + 1).fill(0); cache[0] = cache[1] = 1; for (let i = 2; i < n + 1; i++) { let result = 0; for (let j = 0; j < i; j++) { result += cache[j] * cache[i - 1 - j]; } cache[i] = result; } return cache[n]; } const n = 5; console.log(C(n));