Leetcode with Python, Array

Source: Internet
Author: User

118 Pascal ' s Triangle

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]
Class solution (Object):    def generate (self, numrows): "" "        : Type Numrows:int        : Rtype:list[list[int]] "" "        res = [[1]] for        i in range (1,numrows):            res + = [Map (lambda X, y:x+y,res[-1]+[0],[0]+res[-1])]        return res[:numrows]        # [[1]]+[0] [[1],0] # [[    1]]+[0,1]->[[1],0,1] # [[1]]+[[0]]-[    [1],[0]]    # [[1]]+0] Error    # The code is elegant, but slow. The reason lies in the fact that it generates too much L ist while looping    # being careful when NumRows is 0, Res[:numrows] would return [] when it happens
119 Pascal ' s Triangle II

Given an index K, return the kth row of the Pascal ' s triangle.

For example, given k = 3,
Return [1,3,3,1] .

Note:
Could optimize your algorithm to use only O(k) extra space?

Class solution (Object):    def getRow (self, RowIndex): "" "        : Type Rowindex:int        : rtype:list[int]        " " "                res = [1] for        I in range (0, RowIndex):            res = [i+j for i,j in Zip (res + [0], [0] + res)]        return RES
   # list can ' t be added elementwisely with +

Leetcode with Python, Array

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.