Given an integer n, find the first n rows of Pascal's triangle.
Building upon understanding of Pascal's Triangle (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 pascal(n): cache = [] for i in range(n): row = [] for j in range(i + 1): if j == 0 or i == j: row.append(1) else: row.append(cache[i - 1][j - 1] + cache[i - 1][j]) cache.append(row) return cache n = 5 print(pascal(5))
function pascal(n) { const cache = []; for (let i = 0; i < n; i++) { const row = []; for (let j = 0; j < i + 1; j++) { if (j == 0 || i == j) { row.push(1); } else { row.push(cache[i - 1][j - 1] + cache[i - 1][j]); } } cache.push(row); } return cache; } const n = 5; console.log(pascal(n));