Skip to content

78. Subsets

Linjie Pan edited this page Jun 9, 2019 · 1 revision

This problem is similar to 46. Permutations. The difference is when we should put currentList into resultList:

  • In permutation problem, we add current list to result list when the index hit the length of nums;
  • In subset problem, we put current list to result list at the beginning of traversing of each round.
public void traverse(List<List<Integer>> resultList, List<Integer> currentList, int index, int[] nums) {
    resultList.add(new ArrayList<Integer>(currentList)); // put current list to result list at the begining of traversal
    for(int i = index; i < nums.length; i++) {
        currentList.add(nums[i]);
        traverse(resultList, currentList, i + 1, nums);
        currentList.remove(currentList.size() - 1);
    }
}

public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> resultList = new ArrayList<List<Integer>>();
    traverse(resultList, new ArrayList<Integer>(), 0, nums);
    return resultList;
}
Clone this wiki locally