[LeetCode]Pascal's Triangle II

时间:2023-12-23 10:56:14

题目:给定一个行索引index,返回帕斯卡三角形第index层的三角形

算法:生成index层帕斯卡三角形,并返回第index层三角形

public class Solution {
public List<Integer> getRow(int rowIndex) {
if (rowIndex < 0) {
return null;
} List<List<Integer>> pascalTriangle = new ArrayList<List<Integer>>();
for (int i=0; i<=rowIndex; ++i) {
if (i == 0) {
List<Integer> currTriangle = new ArrayList<Integer>();
currTriangle.add(1);
pascalTriangle.add(i, currTriangle);
} else {
List<Integer> currTriangle = new ArrayList<Integer>();
List<Integer> lastTriangle = pascalTriangle.get(i-1); int lastInteger = 0;
for (int j=0; j<lastTriangle.size(); ++j) {
currTriangle.add(lastInteger + lastTriangle.get(j));
lastInteger = lastTriangle.get(j);
}
currTriangle.add(1);
pascalTriangle.add(currTriangle);
}
}// end of for return pascalTriangle.get(rowIndex);
}
}