zoukankan      html  css  js  c++  java
  • 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;
    
        }
  • 相关阅读:
    Linux 文件查询
    Linux 文件与目录的权限
    Linux查看文件内容
    Linux文件与目录管理
    Linux的文件权限
    java 源码编译
    jvm 字节码执行 (二)动态类型支持与基于栈的字节码解释执行
    jvm 字节码执行 (一)方法调用
    玩转mongodb(七):索引,速度的引领(全文索引、地理空间索引)
    玩转mongodb(六):索引,速度的引领(普通索引篇)
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9394415.html
Copyright © 2011-2022 走看看