Given a set of distinct integers, nums, return all possible subsets (the power set). Note: The solution set must not contain duplicate subsets.

Example: Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        //Arrays.sort(nums); 没必要sort,有重复时需要sort
        helper(nums, res, new ArrayList<Integer>(), 0);
        return res;
    }

    private void helper(int[] nums, 
                        List<List<Integer>> res, 
                        List<Integer> clist, 
                        int start) {
        res.add(new ArrayList<Integer>(clist));

        for(int i = start; i < nums.length; i++) {
            clist.add(nums[i]);
            helper(nums, res, clist, i + 1);
            clist.remove(clist.size() - 1);
        }
    }
}

results matching ""

    No results matching ""