长期更新,对使用 Java 刷 LeetCode 过程中一些有趣的题的感想和启发。 解题源代码仓库

题目

题目链接

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

>

在杨辉三角中,每个数是它左上方和右上方的数的和。

示例:

输入: 5

输出: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]

我的思路

显而易见这道题背后是递归的思路,每一行左右两边是两个“1”,中间是由上一排的数字生成。这道题虽然思路很简单,但是我却做了很久都不正确,有些时候发现 outputList 中出现莫名其妙的错位,错乱,让我百思不得其解。

后来才发现,如果你把一个 List<Integer> add 到另外一个 List<List<Integer>> 中,List<List<Integer>> 实际上保留的是 List<Integer> 的地址,所以如果以后再去操作 List<Integer> 的话,List<List<Integer>> 中的数值也会跟着变化,可以说是很坑了。正确的解决方案应该是每一次都 new 一个新的 ArrayList<>()add.

还有就是不能直接讲一个数组赋值给另外一个数组,像 List1 = List2 ,因为这样的给 List1 的其实是 List2 的地址,而不是把内部的值给他。

正确的方法是:

  1. List<Integer> List1 = new ArrayList<Integer>(List2);
  2. List<Integer> List1 = (ArrayList<Integer>)List2.clone()

我的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//解决方法
class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> outputList = new ArrayList<List<Integer>>();
        if (numRows == 0){
            return outputList;
        }
        List<Integer> lastRow = new ArrayList<Integer>();
        lastRow.add(1);
        outputList.add(lastRow);
        if (numRows == 1) {
            return outputList;
        }
        List<Integer> thisRow = new ArrayList<Integer>();
        thisRow.add(1);
        thisRow.add(1);
        outputList.add(thisRow);
        if (numRows == 2) {
            return outputList;
        }
        for (int i = 1;i < numRows - 1;i++) {
            lastRow = new ArrayList<Integer>(thisRow);
            thisRow = new ArrayList<Integer>();
            thisRow.add(1);
            for (int j = 0;j < lastRow.size() - 1;j++) {
                thisRow.add(lastRow.get(j)+lastRow.get(j+1));
            }
            thisRow.add(1);
            outputList.add(thisRow);
        }
        return outputList;
    }
}


发现存在错别字或者事实错误?请麻烦您点击 这里 汇报。谢谢您!