47 permutation II

Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.

 

Example 1:

Input: nums = [1,1,2]
Output:
[[1,1,2],
 [1,2,1],
 [2,1,1]]

Example 2:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 
特点:重复,多种组合;
思路:
1. arrayList; 
2. boolean标识和格式;
 
=========

class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res= new ArrayList<>();
if(nums==null||nums.length==0) {
return res;
}
Arrays.sort(nums);
boolean[] visited= new boolean[nums.length];
for(int i=0;i<nums.length;i++){
visited[i]=false;
}
dfs(nums,res,new ArrayList<Integer>(),visited);
return res;

}
private void dfs(int[] nums, List<List<Integer>>res,List<Integer>subset,boolean[]visited){
if(subset.size()==nums.length){
res.add(new ArrayList<Integer>(subset));
return;
}
for(int i=0;i<nums.length;i++){
if(visited[i]){
continue;
}
if((i>=1 &&nums[i]==nums[i-1])&&(!visited[i-1])){
continue;
}
subset.add(nums[i]);
visited[i]=true;
dfs(nums,res,subset,visited);
subset.remove(subset.size()-1);
visited[i]=false;
}

}

}

posted @ 2022-07-21 05:04  flag!  阅读(28)  评论(0)    收藏  举报