Subsets II

来源:互联网 发布:怎么看对手人群数据 编辑:程序博客网 时间:2024/06/05 05:22

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],  []]
public class Solution {    public List<List<Integer>> subsetsWithDup(int[] num) {        List<List<Integer>> res = new ArrayList<List<Integer>> ();        int[] visited = new int[num.length];        List<Integer> list = new ArrayList<Integer>();        //不要忘记排序        Arrays.sort(num);        for (int i = 0; i <= num.length; i ++) {            //should be careful that i<=num.length,not i<num.length            helper(res, list, num, visited, 0, i);        }        return res;    }        private void helper(List<List<Integer>> res, List<Integer> list,         int[] num, int[] visited, int position, int length){            if (list.size() == length) {                res.add(new ArrayList<Integer>(list));                return;            }            for (int i = position; i < num.length; i++) {                //有两道类似题目都出错 是因为写成了:if (i != 0 && num[i] == num[i-1] && num[i -1] == 0) {                //要小心是 visited[i-1] ==0                if (i != 0 && num[i] == num[i-1] && visited[i -1] == 0) {                    continue;                }                list.add(num[i]);                visited[i] = 1;                helper(res, list, num, visited, i+1, length);                list.remove(list.size()-1);                visited[i] = 0;            }    }}


第二遍写 发现可以不用visit数组,可以直接实现

helper 里面 的for 循环里面的 对于枚举的所有数据的操作,是同一层的操作。

例如刚开始 for(i= 0,,,num.length - 1), 都是对于list里面 的第一个位置要存的数据,对于同一层,例如[1,1,1,2], 只取第一个1 即可

public class Solution {    public List<List<Integer>> subsetsWithDup(int[] num) {        List<List<Integer>> result = new ArrayList<List<Integer>>();        if (num == null || num.length == 0) {            return result;        }        Arrays.sort(num);        List<Integer> list = new ArrayList<Integer>();        helper(result, list, num, 0);        return result;    }        private void helper(List<List<Integer>> result, List<Integer> list, int[] num, int position) {        result.add(new ArrayList<Integer>(list));        for (int i = position; i < num.length; i++) {            if (i != position && num[i] == num[i - 1]) {                continue;            }            list.add(num[i]);            helper(result, list, num, i + 1);            list.remove(list.size() - 1);        }    }}


0 0