Given an index k, return the k-th 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?
Note: Could you optimize your algorithm to use only O(k) extra space?
public List<Integer> getRow(int rowIndex) {
if (rowIndex < 0)
return null;
List<Integer> result = new ArrayList<Integer>(rowIndex+1);
result.add(1);
// Build each row one at a time
for (int i = 1; i <= rowIndex; i++) {
int temp1 = 1; // Leading 1
for (int j = 1; j < i; j++) {
int temp2 = result.get(j); // Cache the value before it is overwritten
result.set(j, temp1+temp2);
temp1 = temp2;
}
result.add(1); // Trailing 1
}
return result;
}
Read full article from LeetCode - Pascal's Triangle II | Darren's Blog
No comments:
Post a Comment