Pascal ' s Triangle:
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]
The number of rows is known to generate the Pascal Triangle. In fact, as long as there is layer I, then you can generate the first i+1 layer. Each newly generated layer is added to the final collection.
1 PublicList<list<integer>> Generate (intnumrows) {2list<list<integer>> re =NewArraylist<list<integer>>();3 4 for(inti=0;i<numrows;i++) {5list<integer> temp =NewArraylist<integer>();6 for(intj=0;j<=i;j++) {7 if(J==0 | | j==i)8Temp.add (1);9 ElseTenTemp.add (Re.get (i-1). Get (J-1) +re.get (i-1). Get (j)); One } A Re.add (temp); - } - returnre; the}
Pascal ' s Triangle II:
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?
Almost the same as the first question, except that you do not need to return to the entire triangle and only need to return to the last layer. All you need to do is to maintain the build layer and two ArrayList on the top of it.
1 PublicList<integer> GetRow (intRowIndex) {2list<integer> re =NewArraylist<integer>();3 for(inti=0;i<=rowindex;i++) {4list<integer> temp =NewArraylist<integer>();5 for(intj=0;j<=i;j++) {6 if(J==0 | | j==i)7Temp.add (1);8 Else9Temp.add (Re.get (j-1) +Re.get (j));Ten } OneRe =temp; A } - returnre; -}
[Leetcode] [JAVA] Pascal ' s Triangle I, II