|
| 1 | +# 119. Pascal's Triangle II |
| 2 | +# 🟢 Easy |
| 3 | +# |
| 4 | +# https://leetcode.com/problems/pascals-triangle-ii/ |
| 5 | +# |
| 6 | +# Tags: Array - Dynamic Programming |
| 7 | + |
| 8 | +import timeit |
| 9 | +from typing import List |
| 10 | + |
| 11 | + |
| 12 | +# Iterate over n number of rows, for each row, iterate over the row |
| 13 | +# elements backwards computing their new value as the sum of the element |
| 14 | +# at the same position plus the one at the previous position on the |
| 15 | +# previous row. |
| 16 | +# |
| 17 | +# Time complexity: O(n^2) - We iterate n rows, for each row, we iterate |
| 18 | +# over all the row elements. |
| 19 | +# Space complexity: O(n) - We use an extra array of size n. |
| 20 | +# |
| 21 | +# Runtime 35 ms Beats 77.91% |
| 22 | +# Memory 16.04 MB Beats 96.64% |
| 23 | +class Solution: |
| 24 | + def getRow(self, rowIndex: int) -> List[int]: |
| 25 | + row = [0] * (rowIndex + 1) |
| 26 | + row[0] = 1 |
| 27 | + for i in range(1, rowIndex + 1): |
| 28 | + for j in range(i, 0, -1): |
| 29 | + row[j] += row[j - 1] |
| 30 | + return row |
| 31 | + |
| 32 | + |
| 33 | +def test(): |
| 34 | + executors = [Solution] |
| 35 | + tests = [ |
| 36 | + [0, [1]], |
| 37 | + [1, [1, 1]], |
| 38 | + [3, [1, 3, 3, 1]], |
| 39 | + ] |
| 40 | + for executor in executors: |
| 41 | + start = timeit.default_timer() |
| 42 | + for _ in range(1): |
| 43 | + for col, t in enumerate(tests): |
| 44 | + sol = executor() |
| 45 | + result = sol.getRow(t[0]) |
| 46 | + exp = t[1] |
| 47 | + assert result == exp, ( |
| 48 | + f"\033[93m» {result} <> {exp}\033[91m for" |
| 49 | + + f" test {col} using \033[1m{executor.__name__}" |
| 50 | + ) |
| 51 | + stop = timeit.default_timer() |
| 52 | + used = str(round(stop - start, 5)) |
| 53 | + cols = "{0:20}{1:10}{2:10}" |
| 54 | + res = cols.format(executor.__name__, used, "seconds") |
| 55 | + print(f"\033[92m» {res}\033[0m") |
| 56 | + |
| 57 | + |
| 58 | +test() |
0 commit comments