To get row n, we need row n - 1 first. Each row depends on the previous one, with interior elements being the sum of two adjacent elements from above. Recursion naturally models this dependency: we compute the previous row, then build the current row from it.
rowIndex == 0, return [1].[1].1 to rowIndex - 1:prevRow[i - 1] + prevRow[i] to the current row.1 to complete the row.row.We build the entire triangle iteratively from row 0 up to the target row. Each row is constructed using values from the previous row. Though we store all rows, we only need the last one as our answer.
i has i + 1 elements, all initialized to 1.rowIndex:j:res[i][j] = res[i - 1][j - 1] + res[i - 1][j].res[rowIndex].We only need the previous row to compute the current row, so we don't need to store the entire triangle. We keep one row at a time and build the next row by adding contributions from adjacent elements.
res = [1].0 to rowIndex - 1:nextRow of size len(res) + 1, filled with 0.nextRow[j] and nextRow[j + 1].res with nextRow.res.We can update the row in place by iterating from right to left. This ensures we don't overwrite values we still need. Each element becomes the sum of itself and the element to its left, which matches how Pascal's Triangle is built.
row with rowIndex + 1 elements, all set to 1.1 to rowIndex - 1:i down to 1:row[j - 1] to row[j].row.The values in row n of Pascal's Triangle are the binomial coefficients C(n, 0), C(n, 1), ..., C(n, n). We can compute each coefficient incrementally from the previous one using the formula: C(n, k) = C(n, k - 1) * (n - k + 1) / k.
row = [1].i from 1 to rowIndex:row[last] * (rowIndex - i + 1) / i.row.row.When computing binomial coefficients using the formula C(n, k) = C(n, k-1) * (n - k + 1) / k, the intermediate multiplication can overflow before the division. Always multiply first and divide immediately, or use long types to hold intermediate results before casting back to int.
When updating the row in place, iterating from left to right overwrites values that are still needed for subsequent calculations. You must iterate from right to left so that each element is updated using the original (unmodified) values from the previous logical row.