Discuss
Pick One
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
for(int i = 0; i<numRows;i++){
List<Integer> temp = new ArrayList<Integer>();
if(i==0){
temp.add(1);
result.add(new ArrayList<Integer>(temp));
}
else if(i==1){
temp.add(1);
temp.add(1);
result.add(new ArrayList<Integer>(temp));
}
else{
List<Integer> up = result.get(i-1);
temp.add(1);
for(int j=1;j<i;j++){
temp.add(up.get(j)+up.get(j-1));
}
temp.add(1);
result.add(temp);
}
}
return result;
}
}
虽然算法效率不高但是这是是一个开始!!立一个flag:双十一之前每天至少一刷leetcode,双11奖励自己一个iPad mini或者Sony微单!
别人家的solution:
public class Solution {public List<List<Integer>> generate(int numRows)
{
List<List<Integer>> allrows = new ArrayList<List<Integer>>();
ArrayList<Integer> row = new ArrayList<Integer>();
for(int i=0;i<numRows;i++)
{
row.add(0, 1);
for(int j=1;j<row.size()-1;j++)
row.set(j, row.get(j)+row.get(j+1));
allrows.add(new ArrayList<Integer>(row));
}
return allrows;
}
我每次需要取List<Integer> up = result.get(i-1);消耗时间。
本文介绍了一种生成帕斯卡三角的算法实现,并通过两种不同的方法进行了展示。第一种方法使用了简单的循环来逐层构建帕斯卡三角,而第二种方法则采用了一种更高效的方式,利用列表操作减少重复计算。
1013

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



