已解决
java中的深度复制和浅复制的BUG
来自网友在路上 191891提问 提问时间:2023-11-20 10:40:30阅读次数: 91
最佳答案 问答题库918位专家为你答疑解惑
刷题刷到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);}
}
查看全文
99%的人还看了
相似问题
- FISCO BCOS 3.0【01】搭建第一个区块链网络
- 3-运行第一个docker image-hello world
- Vue入门教学——编写第一个页面
- skynet学习笔记01— skynet开发环境搭建(超详细)与第一个skynet程序
- 第二章: 创建第一个Spring Boot 应用
- 【Linux】:使用git命令行 || 在github创建项目 || Linux第一个小程序——进度条(进阶版本)
- 搭建第一个区块链网络与一键部署WeBASE步骤
- 【Linux】:Linux项目自动化构建工具——make/Makefile || Linux第一个小程序——进度条(简单版本)
- Leetcode41缺失的第一个正数
- 【LearnOpenGL基础入门——2】搭建第一个OpenGL窗口
猜你感兴趣
版权申明
本文"java中的深度复制和浅复制的BUG":http://eshow365.cn/6-40270-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!