Subsets II, Leetcode 解题笔记

Given a collection of integers that might contain duplicates, S, return all possible subsets.

Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:


跟Subset I 一样,同样是DFS操作题,唯一的区别是这次遇到num[]中重复的值直接跳过。

public class Solution {
    public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
        ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> sol = new ArrayList<Integer>();
        dfs(ret, sol, 0, num);
        return ret;
    public void dfs(ArrayList<ArrayList<Integer>> ret, ArrayList<Integer> sol, int index, int[] num){
        if(index == num.length) return;
        for(int i = index; i < num.length; i++){
            ret.add(new ArrayList(sol));
            dfs(ret, sol, i+1, num);
            while(i < num.length-1 && num[i] == num[i+1]){

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s