相比Pascal'sTriangle打印前n行,该题考察空间复杂度,改为O(n),1、使用数据结构:队列,先进先出;2、改变构造方法,从右向左,不会覆盖前一行相同位序的值;
public class Solution {
public List getRow(int rowIndex) {
ArrayList res = new ArrayList();
if(rowIndex < 0) return res;
res.add(1);
for(int i = 1; i <= rowIndex; i++){
for(int j = res.size()-2; j >= 0; j--){//backward from last two ele aimed at the previous row
res.set(j+1, res.get(j)+res.get(j+1)); //similar to deque
}
res.add(1);
}
return res;
}
}
本文介绍了一种改进的帕斯卡三角形生成算法,通过使用队列实现O(n)的空间复杂度,避免了传统方法中对于前n行的重复计算,同时介绍了从右向左构造每一行的方法,确保不覆盖前一行的数据。
983

被折叠的 条评论
为什么被折叠?



