Subsets II, Leetcode 解题笔记

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

Note:
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:

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

跟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>();
        Arrays.sort(num);
        ret.add(sol);
        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++){
            sol.add(num[i]);
            ret.add(new ArrayList(sol));
            dfs(ret, sol, i+1, num);
            sol.remove(sol.size()-1);
            while(i < num.length-1 && num[i] == num[i+1]){
                i++;
            }
        }
    }
}
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s