您的位置:首页 > 其它

[leetcode]Pascal's Triangle II

2014-07-22 01:01 459 查看
Pascal's Triangle II


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:

[leetcode]Pascal's Triangle 几乎一样,用2k个空间就可以搞定

思路2:

对空间进行优化,用k个空间搞定

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