Question
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?


本题难度Easy。

【复杂度】
时间 O(N) 空间 O(N)

【思路】
题目有 Note:Could you optimize your algorithm to use only O(k) extra space?
我们可以使用一个技巧:每层的最后一个元素加个0,这样只要在原数据基础上进行累加即可,该层计算完毕再在最前面插入1,最后返回前把最后那个0去掉即可

[1]0   k=0
[1,1]0 k=1
[1,2,1]0 k=2

【注意】
本题的层数从0开始算。

【代码】

public class Solution {
public List<Integer> getRow(int rowIndex) {
//require
List<Integer> ans=new LinkedList<>();
if(rowIndex<0)
return ans;
ans.add(0);
//invariant
for(int i=0;i<=rowIndex;i++){
//累加
for(int j=0;j<i;j++)
ans.set(j,ans.get(j)+ans.get(j+1));
//累加完毕,在开头插入1
ans.add(0,1);
}
//ensure
ans.remove(ans.size()-1);//去掉0
return ans;
}
}