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]
]

Solution:

没啥好说的,注意某行的长度 = 该行index + 1.

public class Solution 
{
    public List<List<Integer>> generate(int numRows) 
    {
        if(numRows == 0)
            return new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> firstList = new ArrayList<>();
        firstList.add(1);
        result.add(firstList);
        for(int i = 1; i < numRows; i++)
        {
            List<Integer> preList = result.get(i - 1);
            List<Integer> curList = new ArrayList<Integer>();
            curList.add(1);
            for(int j = 1; j < i; j ++)
            {
                curList.add(preList.get(j - 1) + preList.get(j));
            }
            curList.add(1);
            result.add(curList);
        }
        return result;
    }
}

推荐阅读更多精彩内容