LeetCode-Algorithms-[Easy]118. 杨辉三角

    技术2022-07-12  68

    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。 在杨辉三角中,每个数是它左上方和右上方的数的和。

    示例:


    唯一要注意的点是,每一行的row采用ArrayList来保存,这样获取某一个的节点的时候时间复杂度为O(1)

    public List<List<Integer>> generate(int numRows) { List<List<Integer>> ans = new ArrayList<>(); if (numRows == 0) { return ans; } List<Integer> firstRow = new ArrayList<>(); firstRow.add(1); ans.add(firstRow); List<Integer> preRow = firstRow; for (int i = 2; i <= numRows; i++) { List<Integer> row = new ArrayList<>(i); row.add(1); for (int j = 1; j < i - 1; j++) { int num = preRow.get(j - 1) + preRow.get(j); row.add(num); } row.add(1); ans.add(row); preRow = row; } return ans; }
    Processed: 0.009, SQL: 9