题目
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 承接上一题,点击打开链接
2 如果不考虑O(k)空间,只要两个链表就可以完成和前一篇一样
public List<Integer> getRow(int rowIndex) {
List<Integer> pre = new ArrayList<Integer>();
List<Integer> cur = new ArrayList<Integer>();
if(rowIndex==0){
pre.add(1);
return pre;
}
for(int k=1;k<=rowIndex;k++){
cur.add(1);
for(int i=0;i<k-1;i++){
cur.add(pre.get(i)+pre.get(i+1));
}
cur.add(1);
pre = new ArrayList<Integer>(cur);
cur.clear();
}
return pre;
}
3 考虑O(k),其实很简单,只要关心某行的坐标与前一行的坐标关系,就可发现:cur[i] = pre[i]+pre[i-1],但是如果更新cur[i],后续的cur[i+1]就无法计算了,这可怎么办?
4 碰到此类问题,往往可以倒过来输出。(从n+1,n,n-1)这是一个思路技巧,多练习几道就会想到了。
5 但是其中有一些JAVA细节要注意,包括List 的set 函数必须是在有这个项的时候才能使用;K是从0行开始计算的等。
public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> cur = new ArrayList<Integer>();
for(int k=0;k<=rowIndex;k++){
for(int i = k;i>=0;i--){
if(i==k){
cur.add(1);
}
else if(i==0){
cur.set(0,1);
}
else{
cur.set(i,cur.get(i)+cur.get(i-1));
}
}
}
return cur;
}
}
本文介绍如何使用O(k)空间复杂度的方法来获取Pascal三角形的第k行,通过优化算法实现高效的求解过程。

589

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



