我正在使用回溯算法来解决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);
}
}