1. 题目
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
在杨辉三角中,每个数是它左上方和右上方的数的和。
示例:
输入: 5 输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
2. 解答
python3
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows <= 0: return [] rows = [[1]] if numRows == 1: return rows for i in range(numRows-1): cur = [1] if len(rows[i]) == 1: cur.append(1) rows.append(cur) continue for j in range(1, len(rows[i])): cur.append(rows[i][j-1]+rows[i][j]) cur.append(1) rows.append(cur) return rows s = Solution().generate(3) print(s)