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?
分析:
帕斯卡三角,又叫杨辉三角,就下面这种三角:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
用一个长度等于最后一行的数组array,则有;
array[i] = array[i] + array[i-1]
这里看见array[i-1], 应该想到每一趟应该从后往前更新,因为从前往后更新的话,计算array[i+1]需要上一层的array[i], 但上一层的array[i] 已经被这一层的array[i]覆盖。
这道题好像没有用什么特殊的算法,从上到下按直观来就可以了,小技巧在于用了一维数组来更新每一层。
public class Solution {
public List<Integer> getRow(int rowIndex) {
Integer[] res = new Integer[rowIndex+1];
Arrays.fill(res, 0);
res[0] = 1;
for(int i=0; i<rowIndex; i++){
for(int j=rowIndex; j>0; j--){
res[j] = res[j]+res[j-1];
}
}
return Arrays.asList(res);
}
}