title :
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?
code : OJ Test via runtime:48 ms
1 classSolution:2 #@return A list of integers3 defGetRow (Self, rowIndex):4 ifRowIndex = =0:5 return[1]6 ifRowIndex = = 1:7 return[]8Pascal = []9 forIinchRange (1, RowIndex):Ten forJinchRange (len (Pascal)-1): OnePASCAL[J] = Pascal[j] + pascal[j+1] APascal.insert (0,1) - returnPascal
Ideas:
Let's start with the special case.
Each iteration of the array updates each element of the arrays from the previous
And finally a 1 in the first place.
In addition, there are a lot of problems on the Internet is that each round from the backward forward, so the efficiency seems to be higher.
Later, the sequence of traversal is changed from backward to forward, and the result is as follows
OJ Test via runtime:37 ms
Code :
1 classSolution:2 #@return A list of integers3 defGetRow (Self, rowIndex):4 ifRowIndex = =0:5 return[1]6 ifRowIndex = = 1:7 return[]8Pascal = []9 Ten #From start to end One #For i in range (1,rowindex): A #For J in Range (Len (Pascal)-1): - #Pascal[j] = Pascal[j] + pascal[j+1] - #Pascal.insert (0,1) the - #From end to start - forIinchRange (1, RowIndex): - forJinchRange (len (Pascal)-1, 0, 1): +PASCAL[J] = Pascal[j] + pascal[j-1] -Pascal.insert (Len (Pascal), 1) + returnPascal
It is really much faster to traverse backward than to traverse backwards.
Little White does not understand the Python principle, the reasons for the analysis may be as follows:
1. At the beginning of the data insert, it takes a long time to change the position of all subsequent elements in the memory in the array.
2. At the end of the array insert, do not need to change the array before all the elements in memory position, only the last new element to fill the position of the line, so fast?
Leetcode "Pascal ' s Triangle II" Python implementation