--- backtracking set contains the same elements Qiuzi

Contains the same elements set Qiuzi

90. Subsets II (Medium)

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

Subject description:

  Given a set of duplicate element set, which returns all the subsets will not be repeated.

Analysis of ideas:

  Seeking the subset of the set, to resolve backtracking. Because there are duplicate elements, so we first collection will be sorted, then time to add elements to see if the previous one and the same element, and if the same previous element has not been accessed, then skipped.

Code:

class Solution {
    public List<List<Integer>>subsetsWithDup(int []nums){
    List<List<Integer>>res=new ArrayList<>();
    List<Integer>list=new ArrayList<>();
    if(nums==null||nums.length==0)
        return res;
    Arrays.sort(nums); //排序
    boolean []visited=new boolean[nums.length];
    for(int size=0;size<=nums.length;size++){
        backtracking(0,size,nums,visited,res,list);
    }
    return res;
}
public void backtracking(int start,int size,int[]nums,boolean[]visited,List<List<Integer>>res,List<Integer>list){
    if(list.size()==size){
        res.add(new ArrayList<>(list));
        return;
    }
    for(int i=start;i<nums.length;i++){
        if(i!=0&&nums[i]==nums[i-1]&&!visited[i-1])
            continue;
        list.add(nums[i]);
        visited[i]=true; //标记已经访问过
        backtracking(i+1,size,nums,visited,res,list);
        list.remove(list.size()-1);
        visited[i]=false;
    }
}
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11114235.html
Recommended