您的位置:首页 > 编程语言 > Java开发

Leetcode-119. Pascal's Triangle II

2016-10-25 20:54 375 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

——————————————————————————————

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?

这个题目还好吧,粗暴一点就是直接两个数组,优化一点就在一个数组上操作。Your runtime beats 60.27% of java submissions.

public class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> result = new ArrayList<Integer>();

for(int i = 0 ; i <= rowIndex; i ++){
if(0 == i) result.add(1);
else if(1 == i)result.add(1);
else{
for(int j = 0; j < result.size() - 1; j ++){
result.set(j,result.get(j) + result.get(j + 1));
}
result.add(0,1);
}
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法