JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.

image tooltip here

In Pascal’s triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 5 Output:

[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

Code

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> list = new ArrayList<>();

        for(int i = 0; i < numRows; i++){
            // 在开头插入1
            list.add(0, 1);
            // 1,2,1 -> 1,1,2,1
            // 1,3,3,1
            for(int j = 1; j < list.size() - 1; j++){
                list.set(j, list.get(j) + list.get(j + 1));
            }

            res.add(new ArrayList<>(list));
        }
        return res;
    }
}