java添加列表函数,java - 将列表添加到嵌套列表时,为什么需要使用构造函数来制作新的列表实例,而不仅仅是添加现有列表? - SO中文参考 - www.soinside.com...

我正在使用回溯算法来解决leetcode中具有重复值的置换。我把我的解决方案放在下面。基本上,我的想法是使用临时LinkedList(temp)构造可能的置换,当其长度等于数组的长度时,将其添加到答案List>中。我的问题是,将临时列表添加到ans列表中时,如果我只使用ans.add(temp)(如在提交的行中),则ans列表将以一个空列表结尾。并且我发现正确的解决方案是使用ans.add(new LinkedList(temp))。

我的问题是

1。是否使用LinkedList类的构造函数?2.为什么我不能只将临时列表添加到ans列表中?幕后发生了什么?class Solution {

public List> permuteUnique(int[] nums) {

List> ans = new LinkedList<>();

if(nums.length==0)

return ans;

Map map = new HashMap<>();

for(int num : nums){

map.put(num, map.getOrDefault(num,0)+1);

}

backtracking(map,ans,new LinkedList(),nums.length);

return ans;

}

public void backtracking(Map map, List> ans, LinkedList temp, int length){

if(temp.size()==length){

//ans.add(temp); why doesn't this work???

ans.add(new LinkedList(temp));

return;

}

for(Integer key: map.keySet()){

int num = map.get(key);

if(num==0)

continue;

manipulate(map,key,-1);

temp.add(key);

backtracking(map,ans,temp,length);

manipulate(map,key,+1);

temp.remove(temp.size()-1);

}

}

public void manipulate(Map map,int key, int delta){

map.put(key, map.get(key)+delta);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值