当前位置: 首页 > article >正文

java中的深度复制和浅复制的BUG

刷题刷到LeetCode回溯DFS的算法题39题的时候,碰见一个Arraylist里面的bug,其中dfs函数里面的第一个if判断里面的语句

paths.add(path);
path.clear();

其中path是添加了path,但是添加之后path.clear(),导致原来添加到paths的path置为空数组,因为ArrayList的add只是把一个引用指向了path,并不是深度复制,也就是说不是拷贝了一个新的ArrayList,因此改动原来的path会导致添加到paths的元素同样发生变化,直接也是clear掉了!

package org.example.SolutionTest3;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        int n=candidates.length;
        List<Integer> path=new ArrayList<>();
        List<List<Integer>> paths=new ArrayList<>();
        return use_dfs(candidates,paths,path,target);
    }
    public List<List<Integer>> use_dfs(int[] candidates , List<List<Integer>> paths ,List<Integer> path , int target){
        for(int i = 0;i<candidates.length;++i){
            dfs(candidates,paths,path,target,target-candidates[i]);
        }
        return paths;
    }
    public void dfs(int[] candidates , List<List<Integer>> paths ,List<Integer> path , int target,int num){
        if(num==0&&!path.isEmpty()){
            System.out.println("path = " + path);
            paths.add(path);
            path.clear();
            //path=new ArrayList<>();
            return;
        }else if(num<0&&!path.isEmpty()){
            path.remove(path.size()-1);
            return;
        }

        for( int i = 0 ; i<candidates.length;++i){
            int next_num = num-candidates[i];
            if(next_num<0){
                continue;
            }
            path.add(candidates[i]);
            dfs(candidates,paths,path,target , next_num);

        }
    }
    public static void main(String[] args) {
        List<List<Integer>> lists = new Solution().combinationSum(new int[]{
                        2, 3, 6, 7
                },
                7);
        System.out.println(lists);
    }
}

http://www.kler.cn/news/135260.html

相关文章:

  • Linux常见命令手册
  • NVS 错误码对应的原因
  • C# Winform围棋棋盘
  • 音视频项目—基于FFmpeg和SDL的音视频播放器解析(十四)
  • MATLAB中plotmatrix函数用法
  • 【服务器学习】timer定时器模块
  • Python的os.path.join()详解
  • 工作备忘录【react-native】
  • C++实现高频设计模式
  • Docker中快速安装RabbitMQ
  • 【开题报告】基于SpringBoot的二手汽车交易平台的设计与实现
  • HAL库STM32串口开启DMA接收数据
  • PPT基础:编辑顶点
  • stable-diffusion-webui之webui.py
  • 竞赛选题 行人重识别(person reid) - 机器视觉 深度学习 opencv python
  • 【Flink】窗口(Window)
  • 被OpenAI开除后,创始人奥特曼在微软找到了新工作
  • 代码随想录算法训练营第27天|39. 组合总和 40.组合总和II 131.分割回文串
  • 批量下载Sentinel数据脚本2023
  • 线程的面试八股
  • Union(联合体、共用体)
  • Linux创建用户及sumba服务器创建用户
  • 项目交互-选择器交互
  • SASS/SCSS精华干货教程
  • 微信小程序配置企业微信的在线客服
  • QPair的介绍及用法
  • 邮箱设置第三方登录授权码获取
  • 阿里云oss使用签名url上传时的一些配置注意事项
  • storage和正则表达式
  • NPM 与 XUI 共存!Nginx Proxy Manager 搭配 X-UI 实现 Vless+WS+TLS 教程!