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 you optimize your algorithm to use only O(k) extra space?
To use only O(k) extra space, the key is to use a parameter to store the previous value at previous position, and thus reuse the arraylist in each loop.
public class Solution {
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (rowIndex < 0) {
return res;
}
res.add(1);
for (int i = 1; i <= rowIndex; i++) {
int pre = 1;
for (int j = 1; j <= i; j++) {
if (j == i) {
res.add(1);
} else {
int curr = res.get(j);
res.set(j, pre + curr);
pre = curr;
}
}
}
return res;
}
}