1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| class Solution { public List<List<Integer>> permuteUnique(int[] nums) { int numsLength = nums.length; List<List<Integer>> ans = new ArrayList<>(); List<Integer> list = new ArrayList<Integer>(); if(numsLength == 1){ list.add(nums[0]); ans.add(list); return ans; } boolean[] visited = new boolean[numsLength]; Arrays.sort(nums); backtricking(nums,ans,list,visited); return ans; } public void backtricking(int[] nums, List<List<Integer>> ans,List<Integer> list,boolean[] visited){ if(list.size() == nums.length){ ans.add(new ArrayList<>(list)); return; }
for(int i = 0; i < nums.length;i++){ if(i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) continue; if(visited[i]) continue; visited[i] = true; list.add(nums[i]); backtricking(nums,ans,list,visited); list.remove(list.size() - 1); visited[i] = false; }
}
}
|