Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Return
[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
比较简单的题,注意实现的时候不要数组越界,以及更新的过程是从后面到前面,因为我们在使用一个数组存储之前的状态,从前面开始更新后导致后面的值更新错误。
Could you optimize your algorithm to use only O(k) extra space?
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<Integer>();
result.add(1);
if(rowIndex == 0) {
return result;
}
else {
for(int i = 1; i <= rowIndex; i++) {
for(int j = i-1; j >= 1; j--) {
result.set(j, result.get(j) + result.get(j-1));
}
result.add(1);
}
return result;
}
}
没有评论:
发表评论