Topic:
Given numrows, generate the first numrows of Pascal ' s triangle.
For example, given numrows = 5,
Return
[ 1], [ 1,2,1], [ 1,3,3,1], [ 1,4,6,4,1]
Links: http://leetcode.com/problems/pascals-triangle/
A brush, the problem is simple but the solution is not good.
- The first problem is the upper limit of NumRows and range (N), because range starts with 0, so range (numRows-1)
- List.reverse () is in place, the reversed (list) return value is a new list
- cur = cur.extend (second_half) return is None!!! Cur.extend (second_half) is enough, this error is not usually possible at all, too low
- NumRows = = 1 is returned as a special example
There is a summary that seems to avoid 4), often I will use prev, cur two list, if only one word seems to be able to judge a boundary situation less .
1 classsolution (object):2 defGenerate (Self, numrows):3 ifNumRows = =0:4 return []5 ifNumRows = = 1:6 return[[1]]7result = [[1]]8prev = [1]9Cur = []Ten One forRowinchRange (numRows-1): ACur.append (1) - forIdxinchRange (ROW/2): -Cur.append (Prev[idx] + prev[idx + 1]) theSecond_half =reversed (cur) - ifRow% 2: -Cur.append (PREV[ROW/2] + PREV[ROW/2 + 1]) - cur.extend (second_half) + result.append (cur) -Prev, cur =cur, [] + returnResult
118 Pascal ' s Triangle