- 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
- 45 lines of Python from the credited upstream file pascals-triangle.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- 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 generate(self, numRows):7 result = []8 for i in xrange(numRows):9 result.append([])10 for j in xrange(i + 1):11 if j in (0, i):12 result[i].append(1)13 else:14 result[i].append(result[i - 1][j - 1] + result[i - 1][j])15 return result16 17 def generate2(self, numRows):18 if not numRows: return []19 res = [[1]]20 for i in range(1, numRows):21 res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]22 return res[:numRows]23 24 def generate3(self, numRows):25 """26 :type numRows: int27 :rtype: List[List[int]]28 """29 if numRows == 0: return []30 if numRows == 1: return [[1]]31 res = [[1], [1, 1]]32 33 def add(nums):34 res = nums[:1]35 for i, j in enumerate(nums):36 if i < len(nums) - 1:37 res += [nums[i] + nums[i + 1]]38 res += nums[:1]39 return res40 41 while len(res) < numRows:42 res.extend([add(res[-1])])43 return res44 45