Description
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?
Solution
DP
使用O(k)額外空間的話铅鲤,只需要一個(gè)List就可以了声登,然后注意每行需要從后向前遍歷更新值垂蜗。
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList();
if (rowIndex < 0) return row;
for (int i = 0; i <= rowIndex; ++i) {
row.add(1);
for (int j = i - 1; j > 0; --j) {
row.set(j, row.get(j - 1) + row.get(j));
}
}
return row;
}
}