78 Subsets

Given a set ofdistinctintegers,nums, return all possible subsets (the power set).

Note:The solution set must not contain duplicate subsets.

For example,
Ifnums=[1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Solution)

For the given array, the length of all subsets is 2^n because we can determine if each element can be included or not.

So, we have to repeat until 2^n and then, we can include the element which bit is enabled in the binary representation of the current index.

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < Math.pow(2,nums.length); i++) {
            List<Integer> subset = new ArrayList<>();
            for (int j = 0; j < nums.length; j++) {
                if ((1 & (i >> j)) > 0)
                    subset.add(nums[j]);
            }
            result.add(subset);
        }
        return result;
    }
}

Another solution is to use backtracking

public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, 0);
    return list;
}

private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){
    list.add(new ArrayList<>(tempList));
    for(int i = start; i < nums.length; i++){
        tempList.add(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);
    }
}

results matching ""

    No results matching ""