For example, given k = 3,
Return
[1,3,3,1]
.Note:
Could you optimize your algorithm to use only O(k) extra space?
---
Solution: Edit the same array in-place. For index i, since we are going to use indexes i-1 and i to update index i, we need to save the pre-modified value at index i to calculate the next value.
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<>();
list.add(1);
for (int i = 0; i < rowIndex; i++) {
int last = list.get(0);
for (int j = 1; j < list.size(); j++) {
int temp = list.get(j);
list.set(j, last + list.get(j));
last = temp;
}
list.add(1);
}
return list;
}
}
No comments:
Post a Comment