118 Pascal ' s Triangle

Source: Internet
Author: User

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.

    1. The first problem is the upper limit of NumRows and range (N), because range starts with 0, so range (numRows-1)
    2. List.reverse () is in place, the reversed (list) return value is a new list
    3. cur = cur.extend (second_half) return is None!!! Cur.extend (second_half) is enough, this error is not usually possible at all, too low
    4. 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

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.