Leetcode: Subsets


Given an array of integer nums of unique elements, we want to return all of the possible subsets. However, this solution must NOT contain any duplicate subsets, and we want to return the solution in ANY order. Here are the examples:

Example 1:

Input: nums = [1,2,3]

Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]


Example 2:

Input: nums = [0]

Output: [[],[0]]


And the Constraints are as follows:

1 <= nums.length <= 10

-10 <= nums[i] <= 10

All the numbers of nums are unique.


and now we have a structure that will apply to many backtracking questions and we definitely use backtracking here. We first sort the arrays, then backtrack a list, then return the backtrack. In the backtracking step, we go through and add something new to the list in a temporary list, then backtrack, then remove the element from the temporary list. The final solution is as follows: 

public class Solution {

    public List<List<Integer>> subsets(int[] nums) {

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

        //sort the array

        Arrays.sort(nums);

        //backtrack this stuff   

        backtrack(list, new ArrayList<>(), nums, 0);

        //return the list

        return list;

    }    


    public void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] nums, int start) {

        //add new arraylist

        list.add(new ArrayList<>(tempList));

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

            //add element from temporary list

            tempList.add(nums[i]);

            backtrack(list, tempList, nums, u + 1);

            //remove the item from the list and move to the next step

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

        }

    }

}

Comments

Popular Posts