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

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.lryc.cn/news/234836.html

相关文章:

  • 计算机毕业设计 基于SpringBoot的车辆网位置信息管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解
  • 集软件库、论坛、社区、工具箱、积分商城、会员体系、在线商城一体的后台系统+HBuilderX 前端软件社区
  • 【解决Qt编译报错:-1: warning: **.so, not found(try using -rpath or -rpath-link)】
  • 关于数据mysql ->maxwell->kafka的数据传输
  • 【linux】查看CPU的使用率
  • 【系统稳定性】1.6 黑屏(三)
  • 《使用EasyExcel在Excel中增加序号列的方法》
  • 【Linux】安全审计-audit
  • Linux 之查看标准错误码工具
  • Git企业开发级讲解(五)
  • 目录自动清洗
  • c++实现Any类,让一个类型指向其他任意类型
  • os.path.join函数用法
  • vscode Prettier配置
  • MLC-LLM 支持RWKV-5推理以及对RWKV-5的一些思考
  • WPF中行为与触发器的概念及用法
  • 2023-2024华为ICT大赛-计算赛道-广东省省赛初赛-高职组-部分赛题分析【2023.11.18】
  • 『 MySQL数据库 』数据库之表的约束
  • flink 8081 web页面无法被局域网内其他机器访问
  • 零基础安装分布式数据服务注册系统
  • 2023最新最全【OpenMV】 入门教程
  • 【Java并发编程三】线程的基本使用一
  • 企业邮箱认证指南:安全与高效的邮箱认证方法
  • Django(八、如何开启事务、介绍长见的字段类型和参数)
  • 机器学习第5天:多项式回归与学习曲线
  • MSYS2介绍及工具安装
  • Swift开发中:非逃逸闭包、逃逸闭包、自动闭包的区别
  • 栈结构应用-进制转换-辗转相除法
  • 【Azure 架构师学习笔记】-Azure Storage Account(6)- File Layer
  • idea 环境搭建及运行java后端源码