LeetCode118-杨辉三角(水题,犯了Java引用的错误)

List<Integer> temp = new ArrayList<>();

        temp.add(1);

//此时是[1]
        result.add(temp);


        if(numRows==1)
            return result;

        temp.add(1);
//此时是[1,1]
        result.add(temp);


        if(numRows==2)
            return result;

我以为在2行的时候,这样就返回[[1],[1,1]]了。

但是结果是这样的

数组不是把temp值存进去,而是存temp引用的对象。所以说更像一个指针。

temp的值改了之后,所有和tmp指向同一个地方的都会被改。

改成这样即可

List<Integer> temp = new ArrayList<>();

        temp.add(1);

        result.add(temp);
        if(numRows==1)
            return result;

//从新给temp分配内存
        temp = new ArrayList<>();

        temp.add(1);
        temp.add(1);

        result.add(temp);

        if(numRows==2)
            return result;

因为第一个temp指向的内存区域,被数组[0]指向了,所以不会被回收。

temp只是一个变量,给他新的内存区域,再操作即可。

其余的还挺简单的,每一行在index位置的数字就是上一行的index-1 和 index 数字之和。

每行的开头和末尾都是1,只要处理中间部分即可。

public static List<List<Integer>> generate(int numRows) {

        //0行返回什么?

        //设置好第一行,后续的自动生成即可
        List<List<Integer>> result = new ArrayList<>();

        if (numRows==0)
            return result;

        List<Integer> temp = new ArrayList<>();

        temp.add(1);

        result.add(temp);
        if(numRows==1)
            return result;

        temp = new ArrayList<>();

        temp.add(1);
        temp.add(1);

        result.add(temp);

        if(numRows==2)
            return result;

        //从第三行开始即可
        for(int i=2;i<numRows;i++){

            //构造每一行,第n行的个数是n,第一个和最后一个数字都是1

            List<Integer> current = new ArrayList<>();

            //
            current.add(1);

            List<Integer> last = result.get(i-1);

            //中间就是j-1,j两个位置
            //第i行的个数是i+1个,因为i是比行数少一的
            for(int j=1;j<i;j++){
                current.add(last.get(j-1)+last.get(j));
            }

            //
            current.add(1);

            result.add(current);


        }

        return result;

    }

猜你喜欢

转载自www.cnblogs.com/weizhibin1996/p/9394415.html
今日推荐