Leetcode----------Pascal ' s Triangle II

Source: Internet
Author: User

Topic Pascal ' s Triangle II
Pass Rate 29.8%
Difficulty Easy

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?

First of all, Pascal's Triangle and Pascal's Triangle II two topics together, both of which are the treatment of Pascal's Triangle;

But the parameter meaning given by the two topics is very different, Pascal's Triangle is the given numrows (i.e. the total number of rows); Pascal's Triangle II gives the rowindex (the index of the row, which is the first line), because Pascal's The subscript of the triangle is starting from 0, so the initialization of the two topics is a distinction that requires special attention. Especially with regard to the treatment of 0;

Because Pascal's triangle is nested in layers, the next layer of elements is determined by the elements of the previous layer, but this topic also makes a request for space, so in the process of loop call every row to the previous row of the space to clear, so as to ensure that the space complexity is O (k).

Java code:

 Public classSolution { PublicList<integer> GetRow (intRowIndex) {List<Integer> list =NewArraylist<integer>(); List<Integer> List2 =NewArraylist<integer>(); if(rowindex<0)returnlist;  for(inti=0;i<=rowindex;i++){            if(i==0) {List2.add (1); }Else              for(intj=0;j<=i;j++){                if(J==0 | | j==i) {List2.add (1); }                Else{List2.add (List.get (J-1) +List.get (j)); }} List<Integer> temp =list; List=List2; List2=temp;        List2.clear (); }        returnlist; }}

Leetcode----------Pascal ' s Triangle II

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.