package _118;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* https://leetcode.cn/problems/pascals-triangle/
* 118. 杨辉三角
* 给定一个非负整数 numRows,生成「杨辉三角」的前 numRows 行。
* 在「杨辉三角」中,每个数是它左上方和右上方的数的和。
* 2022-08-29 14:54
*/
public class Test {
public static void main(String[] args) {
int numRows = 5;
Solution s = new Solution();
List<List<Integer>> list = s.generate(numRows);
System.out.println(list);
}
}
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> list = new LinkedList<>();
List<Integer> tempList= new LinkedList<>();
tempList.add(1);
list.add(tempList);
//一共有numRows层,从第二层开始
for(int i = 2;i<=numRows;i++){
//第i行有i个元素
// 1
// 注意,LinkedList的index 是从0开始的
//上一行元素
List<Integer> preList= tempList;
tempList.clear();
tempList.add(1);
for(int j = 0;j< i-2;j++){
tempList.add(preList.get(j)+preList.get(j+1));
}
tempList.add(1);
list.add(tempList);
}
return list;
}
}
/**
* tempList
* 修改这个 把之前的数据也修改了
*
* ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j) 这样获得上一行的数据
*
* List row = new ArrayList(); 用这个添加新的一行的元素
*/
class Solution2 {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
for (int i = 0; i < numRows; ++i) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j <= i; ++j) {
if (j == 0 || j == i) {
row.add(1);
} else {
row.add(ret.get(i - 1).get(j - 1) + ret.get(i - 1).get(j));
}
}
ret.add(row);
}
return ret;
}
}