标签:
题目:
Given numRows, generate the first numRows of Pascal‘s triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
链接: http://leetcode.com/problems/pascals-triangle/
一刷,这道题简单却解得并不好。
有一个总结似乎可以避免4),经常我会用prev, cur两个list,如果只用一个的话似乎可以少判断一次边界情况。
1 class Solution(object): 2 def generate(self, numRows): 3 if numRows == 0: 4 return [] 5 if numRows == 1: 6 return [[1]] 7 result = [[1]] 8 prev = [1] 9 cur = [] 10 11 for row in range(numRows - 1): 12 cur.append(1) 13 for idx in range(row / 2): 14 cur.append(prev[idx] + prev[idx + 1]) 15 second_half = reversed(cur) 16 if row % 2: 17 cur.append(prev[row / 2] + prev[row / 2 + 1]) 18 cur.extend(second_half) 19 result.append(cur) 20 prev, cur = cur, [] 21 return result
标签:
原文地址:http://www.cnblogs.com/panini/p/5610167.html