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;
    
        }
  • 相关阅读:
    [arXiv18]更快的基于非二叉化自底向上策略的转移系统成分句法分析
    [AAAI18]面向序列建模的元多任务学习
    [COLING18]两种成分句法分析的局部特征模型
    [ACL18]基于RNN和动态规划的线性时间成分句法分析
    成分句法分析综述
    [NAACL16]RNN文法
    [TACL17]基于中序转移的成分句法分析
    K-摇臂赌博机算法与实现
    关于JVM案例分析(四)
    关于JVM案例分析(三)
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9394415.html
Copyright © 2011-2022 走看看