| 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