您的位置:首页 > 其它

Pascal's Triangle II

2017-01-07 03:14 239 查看
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?

有一种只需要开辟一个数组的解法,有时间补上。

这道题的思路跟第一问很像,一种解决思路是使用两个数组,pre, cur 不断的更新。

代码:

public List<Integer> getRow(int rowIndex) {
//可以用数学公式计算
List<Integer> cur = new ArrayList<>();
List<Integer> pre = new ArrayList<>();
pre.add(1);
if(rowIndex == 0) return pre;
for(int i=1;i<=rowIndex;i++){
cur.clear();
cur.add(1);
for(int j=1;j<pre.size();j++){
cur.add(pre.get(j) + pre.get(j-1));
}
cur.add(1);
//pre.clear();
//System.out.println(cur.size());
pre.clear();
pre.addAll(cur);
}
return pre;
}


还有一种解法:只需要一个数组

public List<Integer> getRow(int rowIndex) {
List<Integer> list = new ArrayList<Integer>();
if(rowIndex <0){
return list;
}
for(int i=0;i<rowIndex+1;i++){
//首位的1
list.add(0,1);
for(int j=1;j<list.size()-1;j++){
list.set(j, list.get(j)+list.get(j+1));
}
//末尾的1就不动它
}
return list;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: