话不多说直接上代码
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if (nums == null || nums.length == 0) return res;
dfs(nums,0);
return res;
}
public void dfs(int[] nums,int idx) {
if (idx == nums.length) {
List<Integer> sub = new ArrayList<>();
for(int m : nums)
sub.add(m);
res.add(new ArrayList<>(sub));
return;
}
for (int i = idx; i < nums.length; i++) {
if(!check(nums,idx,i))
continue;
swap(nums,idx,i);
dfs(nums,idx+1);
swap(nums,idx,i);
}
}
public void swap(int[] nums,int i,int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public boolean check(int[] nums,int idx,int i){
/*这里的意思是假设从nums[idx]到nums[i]之前存在与nums[i]相同的数,那么之前肯定已经交换过了,
所以这一次不同再次交换了
*/
for(int k=idx;k<i;k++)
if(nums[k]==nums[i])
return false;
return true;
}
}