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> generate(int numRows) 
    {
        if(numRows == 0)
            return new ArrayList<>();
        List> result = new ArrayList<>();
        List firstList = new ArrayList<>();
        firstList.add(1);
        result.add(firstList);
        for(int i = 1; i < numRows; i++)
        {
            List preList = result.get(i - 1);
            List curList = new ArrayList();
            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;
    }
}

你可能感兴趣的:(118. Pascal's Triangle)