• 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;
    
        }
  • 相关阅读:
    使用QOAuth来进行新浪/腾讯微博验证(二)
    很不错的Utility库,C#4扩展 各种功能齐全,两行代码搞定图片转字符
    使用QOAuth来进行新浪/腾讯微博验证(一)
    可怜的小猪&香农熵
    消息队列MQ如何保证消息不丢失
    40 亿个 QQ 号码如何去重,bitmap去重
    参数的设置
    自动化测试的十个要点
    LR学习中的一个低级错误
    Windows下用CMake编译libuv
  • 原文地址:https://www.cnblogs.com/weizhibin1996/p/9394415.html
Copyright © 2020-2023  润新知