118. Pascal’s Triangle
题目
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]
]
翻译
给定numRows,生成Pascal三角形的第一个numRows。
例如,给定numRows = 5,
返回
[
[1],
[1,1],
[1,2,1]
[1,3,3,1],
[1,4,6,4,1]
]
解题思路
其中主要要注意的是oldList的清空问题,还有要add时候要添加的是新建的newList,而不能用oldList,因为添加的是引用,oldList会被修改,之后值就会变化,达不到目的
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> oldList = new ArrayList<>();
for(int i=0;i<numRows;i++){
List<Integer> newList = new ArrayList<>();
newList.add(1);
for(int j=0;j<i;j++){
if(j+1 == i){
newList.add(1);
}
else{
newList.add(oldList.get(j)+oldList.get(j+1));
}
}
oldList.clear();
oldList = new ArrayList<>(newList);
result.add(newList);
}
return result;
}
}
欢迎加入中科院开源软件自习室:631696396