【LeetCode with Python】 Pascal's Triangle

来源:互联网 发布:three.min.js下载 编辑:程序博客网 时间:2024/05/16 00:34
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/pascals-triangle/
题目类型:数组
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/3465679

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]]

输出帕斯卡三角,明白帕斯卡三角的定义即可简单解题。


class Solution:    # @return a list of lists of integers    def generate(self, numRows):        rows = []        if numRows <= 0:            return rows         if numRows >= 1:            rows.append([1])        if numRows >= 2:            rows.append([1, 1])        if numRows >= 3:            need_rowsnum = numRows - 2            last_row = [1, 1]            for i in range(0, need_rowsnum):                new_row = [1]                for j in range(1, len(last_row)):                    new_row.append(last_row[j - 1] + last_row[j])                new_row.append(1)                rows.append(new_row)                last_row = new_row        return rows

原创粉丝点击