给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出: [ [1,1,2], [1,2,1], [2,1,1] ]
回溯
1、首先选择第一个数字,看这个数字的值是否已经作为过第一个数字,若是没有做过,那么就选择这个数字作为第一个数字,之后将这个数字的标志位置为true。
2、之后选择第二个数字,这个数字没被使用过,并且这个值也没有在第二个位置上出现过,就可以将这个数字作为第二个数字。
3、以此类推。
4、最后,当数组中的数字全部使用过了,那个就可以得到一个结果了。
5、之后重复上述步骤。
class Solution {
boolean[] visited;
List<List<Integer>> res;
public List<List<Integer>> permuteUnique(int[] nums) {
int len = nums.length;
visited = new boolean[len];
res = new ArrayList<>();
int[] temp = new int[len];
backtracking(nums, 0, temp);
return res;
}
public void backtracking(int[] nums, int count, int[] temp){
if(count >= nums.length){
List<Integer> list = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
list.add(temp[i]);
}
res.add(list);
return;
}
Set<Integer> set = new HashSet<>();
for(int i = 0; i < nums.length; i++) {
if(!visited[i]&&!set.contains(nums[i])){
visited[i] = true;
temp[count] = nums[i];
set.add(nums[i]);
back(nums, count+1, temp);
visited[i] = false;
}
}
}
}
672

被折叠的 条评论
为什么被折叠?



