2-20-lc47全排列II

47. 全排列 II

 1 class Solution {
 2     public List<List<Integer>> permuteUnique(int[] nums) {
 3         List<List<Integer>> ans = new ArrayList<>();
 4         int[] visited = new int[nums.length];
 5         Arrays.sort(nums);
 6         Backtrack(nums,visited,new ArrayList<>(),ans);
 7         return ans;
 8     }
 9     private void Backtrack(int[] nums,int[] visited,ArrayList<Integer> tmp,List<List<Integer>> ans){
10         if(tmp.size()==nums.length){
11             ans.add(new ArrayList<>(tmp));
12             return;
13         }
14         for(int i =0;i<nums.length;i++){
15             if(visited[i]==1||(i>0&&visited[i-1]==0&&nums[i-1]==nums[i]))continue;
16             //if(visited[i]==1)continue;
17             tmp.add(nums[i]);
18             visited[i]=1;
19             Backtrack(nums,visited,tmp,ans);
20             visited[i]=0;
21             tmp.remove(tmp.size()-1);
22         }
23     }
24 }

 

posted @ 2022-02-21 00:00  Wind·Chaser  阅读(18)  评论(0编辑  收藏  举报