LeetCode 90. Subsets II

题目描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

AC代码

是 LeetCode 78 的升级版,输入序列可能包含了重复,为了去除重复,所以要事先对输入序列进行排序。

public class _90subsetsWithDup {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> resList = new ArrayList<>();
        if(nums == null || nums.length == 0) return resList;
        Arrays.sort(nums);  //因为要判断重复,所以必须要先排序
        backtrack(resList, new ArrayList<Integer>(), nums, 0);
        return resList;
    }
    private void backtrack(List<List<Integer>> resList, ArrayList<Integer> tmpList, int[] nums, int start){
        resList.add(new ArrayList(tmpList));
        for(int i = start;i < nums.length;i++){  //以 i 开头到结尾的所有的子序列
            if(i > start && nums[i] == nums[i - 1]) continue; //注意对 i > start 的理解
            tmpList.add(nums[i]);
            backtrack(resList, tmpList, nums, i + 1);
            tmpList.remove(tmpList.size() - 1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/tkzc_csk/article/details/82120923
今日推荐