Leetcode 119. Pascal's triangle II

Source: Internet
Author: User

Analysis

Easy to use

Source

Https://leetcode.com/problems/pascals-triangle-ii/

Question

Given a non-negative IndexKWhereK≤ 33, returnKTh index row of the Pascal's triangle.

Note that the row index starts from 0.

 

In Pascal's triangle, each number is the sum of the two numbers directly abve it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Cocould you optimize your algorithm to use onlyO(K) Extra space?

Answer

1 package leetcode; 2 3 Import Java. util. arraylist; 4 Import Java. util. list; 5 6 public class l119_pascaltriangleii {7 public list <integer> getrow (INT rowindex) {8 If (rowindex <0) 9 return NULL; 10 // The row K starting from 0, that is, (k + 1) corresponds to the last row of the Fibonacci series 11 int listlen = rowindex + 1; 12 list <integer> List = new arraylist <integer> (); // record the current layer value 13 for (INT I = 0; I <listlen; I ++) // I don't know why this sentence is written here faster than the outer layer of the Layer 2 loop below, 14 list. add (1); // All values are assigned with 1, the initial test value, and the boundary value of each layer is 15 for (INT I = 0; I <listlen; I ++) {16 for (Int J = I-1; j> 0; j --) {// assign a value to a row from right to left, avoid using two integers 17 list to modify the next number. set (J, list. get (J-1) + list. get (j); 18} 19} 20 return list; 21} 22 public static void main (string [] ARGs) {23 long time1 = system. currenttimemillis (); 24 l119_pascaltriangleii l119 = new l119_pascaltriangleii (); 25 system. out. println (l119.getrow (10); // The K row starting from 0, that is, (k + 1) corresponds to the last row of the Fibonacci series 26 Long time2 = system. currenttimemillis (); 27 system. out. println (time2-time1); 28} 29}

 

 

Leetcode 119. 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.