Subsets II

Subsets II

问题:

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.

思路:

  dfs + 回溯

我的代码:

public class Solution {

    public List<List<Integer>> subsetsWithDup(int[] num) {

        if(num == null || num.length == 0)  return rst;

        List<Integer> list = new ArrayList<Integer>();

        Arrays.sort(num);

        helper(list, num, 0);

        return rst;

    }

    private List<List<Integer>> rst = new ArrayList<List<Integer>>();

    public void helper(List<Integer> list, int[] candidates, int start)

    {

        rst.add(new ArrayList(list));

        for(int i = start ; i < candidates.length; i++)

        {

            if( i != start && candidates[i] == candidates[i-1]) continue;

            list.add(candidates[i]);

            helper(list, candidates, i + 1);

            list.remove(list.size() - 1);

        }

    }

}
View Code

学习之处:

  真正理解了程序,也就明白了if( i != start && candidates[i] == candidates[i-1]) continue;判断的精华所在了。

你可能感兴趣的:(set)