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

题意:著名的杨辉三角形,解题思路比较巧妙,每一行都比上一行多一个数字,开始和末尾都是1,我们只需要动态的改变中间的内容就可以,很巧妙的代码~

java代码:

class Solution {
    public List> generate(int numRows) {
        List> pascal = new ArrayList>();
        ArrayList row = new ArrayList();
        for (int i = 0; i < numRows; i++) {
            row.add(0, 1);
            for (int j = 1; j < row.size() - 1; j++)
                row.set(j, row.get(j) + row.get(j + 1));
            pascal.add(new ArrayList(row));
        }
        return pascal;
    }
}

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