118. Pascal's Triangle
Given a non-negative integer numRows, generation ago with numRows Yang Hui Triangle.
In Pascal's Triangle, each number is the number of its top left and top right and.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/pascals-triangle
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle=new ArrayList<List<Integer>>();
if(numRows==0)
{
return triangle;
}
triangle.add(new ArrayList<>());
triangle.get(0).add(1);
for(int rowNum=1;rowNum<numRows;rowNum++)
{
List<Integer> row=new ArrayList<>();
List<Integer> prevRow = triangle.get(rowNum-1);//前一行的所有元素
row.add(1);//第一个元素为1
for(int i=1;i<rowNum;i++)
{
row.add(prevRow.get(i-1)+prevRow.get(i));//之后的元素等于其左上角元素加其上方元素
}
row.add(1);//最后一个元素为1
triangle.add(row);//将新一行加入数组中
}
return triangle;
}
}