自己建立网站教程,wordpress网站的优化,网站制作多少钱资讯,优秀网站建设官网刷题刷到LeetCode回溯DFS的算法题39题的时候,碰见一个Arraylist里面的bug,其中dfs函数里面的第一个if判断里面的语句
paths.add(path);
path.clear();其中path是添加了path,但是添加之后path.clear(),导致原来添加到paths的path置为空数组,因为ArrayList的add只是把一个引用指…刷题刷到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 ListListInteger combinationSum(int[] candidates, int target) {int ncandidates.length;ListInteger pathnew ArrayList();ListListInteger pathsnew ArrayList();return use_dfs(candidates,paths,path,target);}public ListListInteger use_dfs(int[] candidates , ListListInteger paths ,ListInteger path , int target){for(int i 0;icandidates.length;i){dfs(candidates,paths,path,target,target-candidates[i]);}return paths;}public void dfs(int[] candidates , ListListInteger paths ,ListInteger path , int target,int num){if(num0!path.isEmpty()){System.out.println(path path);paths.add(path);path.clear();//pathnew ArrayList();return;}else if(num0!path.isEmpty()){path.remove(path.size()-1);return;}for( int i 0 ; icandidates.length;i){int next_num num-candidates[i];if(next_num0){continue;}path.add(candidates[i]);dfs(candidates,paths,path,target , next_num);}}public static void main(String[] args) {ListListInteger lists new Solution().combinationSum(new int[]{2, 3, 6, 7},7);System.out.println(lists);}
}