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