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

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

    Example:

    1. Input: 5
    2. Output:
    3. [
    4. [1],
    5. [1,1],
    6. [1,2,1],
    7. [1,3,3,1],
    8. [1,4,6,4,1]
    9. ]

    题意

    生成前n行帕斯卡(杨辉)三角形。

    思路

    直接模拟操作生成每一行。


    代码实现

    1. class Solution {
    2. public List<List<Integer>> generate(int numRows) {
    3. List<List<Integer>> ans = new ArrayList<>();
    4. if (numRows == 0) {
    5. return ans;
    6. }
    7. ans.add(new ArrayList<>());
    8. ans.get(0).add(1);
    9. for (int i = 1; i < numRows; i++) {
    10. ans.add(new ArrayList<>(ans.get(i - 1)));
    11. List<Integer> curRow = ans.get(i);
    12. for (int j = i; j >= 1; j--) {
    13. if (j == i) {
    14. curRow.add(1);
    15. } else {
    16. curRow.set(j, curRow.get(j) + curRow.get(j - 1));
    17. }
    18. }
    19. }
    20. return ans;
    21. }
    22. }