LintCode 18. 带重复元素的子集

给定一个可能具有重复数字的列表,返回其所有可能的子集


public class Solution {
    /**
     * @param nums: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        // write your code here
        List<List<Integer>> list = new ArrayList<>();
        if (nums == null) {
            return null;
        }
        Arrays.sort(nums);
        List<Integer> tmplist = new ArrayList<>();
        int[] visited = new int[nums.length];
        for (int i = 0; i < visited.length; i++) {
            visited[i] = 0;
        }
        for (int i = 0; i <= nums.length; i++) {
            tmplist.clear();
            DFS(list, tmplist, nums, i, 0, visited);
        }
        return list;
    }

    private void DFS (List<List<Integer>> list, List<Integer> tmplist, int[] nums, int size, int start, int[] visited) {
        if (tmplist.size() == size && !list.contains(tmplist)) {
            list.add(new ArrayList<>(tmplist));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            tmplist.add(nums[i]);
            visited[i] = 1;
            DFS(list, tmplist, nums, size, i+1, visited);
            visited[i] = 0;
            tmplist.remove(tmplist.size() - 1);
        }
    }
}

阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页