题目:
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?
题意:
也是杨辉三角,但是这里是输入某行 ,同时输出那一行的 数,要求复杂度为O(n)
解题思路:
还是那个规律:
每个数都是它左上方与它右上方的和
用数组表示:
a[i][j] = a[i-1][j-1]+a[i-1][j]
这里我们直接从后面计算,避免了前面数据被覆盖。满足空间复杂度为O(n)
代码:
public ArrayList<Integer> getRow(int rowIndex) {
if(rowIndex < 0) {
return null;
}
ArrayList<Integer> list = new ArrayList<Integer>();
for(int i=0;i<rowIndex+1;i++) {
for(int j=i-1;j>0;j--) {
list.set(j, list.get(j)+list.get(j-1));
}
list.add(1);
}
return list;
}