LeetCode | 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] ]
//杨辉三角:每一行,头尾为1,中间元素为其上一行两肩位置元素之和 //第i行row的长度为i public class Solution { public List<List<Integer>> generate(int numRows) { List<List<Integer>> result = new ArrayList<List<Integer>>(); if(numRows < 1) return result; List<Integer> preRow = new ArrayList<Integer>(); preRow.add(0); //表示上一行Row for(int i=1; i<=numRows; i++){ //每一行Row的长度就为i List<Integer> curRow = new ArrayList<Integer>(); for(int j=0; j<i; j++){ //填充当前行 if(j < 1){ //head curRow.add(1); }else if(j >= preRow.size()){ //tail curRow.add(1); }else{ curRow.add(preRow.get(j-1) + preRow.get(j)); } } preRow = curRow; result.add(curRow); } return result; } }