This question on LeetCode is a similar question to the Permutations question I did yesterday. But it is more tricky and interesting to solve it. Today is totally another brainstorming day.
Question
Solution
Backtracking
This approach generates all possible subsets of nums by considering whether or not to include each element in the subset. The time complexity of this algorithm is O(2^N), where N is the length of the input array, since there are 2^N possible subsets.
// O(2^N) classSolution { private List<List<Integer>> res = newArrayList(); public List<List<Integer>> subsets(int[] nums) { helper(nums, 0, newArrayList<>()); return res; }
privatevoidhelper(int[] nums, int index, List<Integer> list) { if(index >= nums.length) { res.add(newArrayList<>(list)); return; } list.add(nums[index]); helper(nums, index + 1, list);
list.remove(list.size()-1); helper(nums, index + 1, list); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = newArrayList<>(); backtrack(nums, 0, newArrayList<>(), res); return res; } privatevoidbacktrack(int[] nums, int start, List<Integer> curr, List<List<Integer>> res) { // Eveytime we add curr into res even if curr is empty list res.add(newArrayList<>(curr)); // use i=start to avoid containing duplicate subsets for (inti= start; i < nums.length; i++) { curr.add(nums[i]); backtrack(nums, i + 1, curr, res); curr.remove(curr.size() - 1); } } }
Brute force
At first, I thought this solution was lousy…and I got the Time Limit Exceeded.