Unique Subsets

来源:互联网 发布:学电脑编程能干什么 编辑:程序博客网 时间:2024/06/06 03:07

Unique Subsets

Given a list of numbers that may has duplicate numbers, return all possible subsets.

Example

If S = [1,2,2], a solution is:

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

    public ArrayList<ArrayList<Integer>> subsetsWithDup(ArrayList<Integer> S) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        if (S == null || S.size() == 0) {            return result;        }        Collections.sort(S);        ArrayList<Integer> path = new ArrayList<Integer>();        dfs(result, path, S, 0);        return result;    }    private void dfs(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> path,         ArrayList<Integer> S, int pos){        result.add(new ArrayList<Integer>(path));        for (int i = pos; i < S.size(); i++) {            if (i > pos && S.get(i) == S.get(i - 1)) {                continue;            }            path.add(S.get(i));            dfs(result, path, S, i + 1);            path.remove(path.size() - 1);        }    }
 思路:

duplication发生在当取完一种,后面是重复数字,不能再取。横向比较


0 0
原创粉丝点击