其他分享
首页 > 其他分享> > 47 permutation II

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;
}

}

}

标签:subset,nums,int,47,permutation,II,boolean,res,visited
来源: https://www.cnblogs.com/LLflag1/p/16500529.html