题目描述:
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?
解题思路:
- 这题与上题的思路大致相同,不过这一题的迭代是在同一个集合内
- 既然在同一个数组内迭代,那么就必须考虑集合内元素可能重叠
- 为了避免重叠,需要从集合的后面向前面遍历
代码如下:
public ArrayList<Integer> getRow(int rowIndex) {
ArrayList<Integer> list = new ArrayList<>();
if(rowIndex <= 0) return list;
rowIndex++;
list.add(1);
for(int i = 1; i < rowIndex; i++){
for(int j = i - 1; j > 0; j--){
list.set(j,list.get(j) + list.get(j - 1));
}
list.add(1);
}
return list;
}