- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 56 lines of Python from the credited upstream file pascals-triangle-ii.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 6 def getRow(self, rowIndex):7 result = [0] * (rowIndex + 1)8 for i in xrange(rowIndex + 1):9 old = result[0] = 110 for j in xrange(1, i + 1):11 old, result[j] = result[j], old + result[j]12 return result13 14 def getRow2(self, rowIndex):15 """16 :type rowIndex: int17 :rtype: List[int]18 """19 row = [1]20 for _ in range(rowIndex):21 row = [x + y for x, y in zip([0] + row, row + [0])]22 return row23 24 def getRow3(self, rowIndex):25 """26 :type rowIndex: int27 :rtype: List[int]28 """29 if rowIndex == 0: return [1]30 res = [1, 1]31 32 def add(nums):33 res = nums[:1]34 for i, j in enumerate(nums):35 if i < len(nums) - 1:36 res += [nums[i] + nums[i + 1]]37 res += nums[:1]38 return res39 40 while res[1] < rowIndex:41 res = add(res)42 return res43 44 454647class Solution2(object):48 49 def getRow(self, rowIndex):50 result = [1]51 for i in range(1, rowIndex + 1):52 result = [1] + [result[j - 1] + result[j] for j in xrange(1, i)] + [1]53 return result54 55 56