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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容