Given a set of distinct integers, nums, return all possible subsets
(the power set).Note: The solution set must not contain duplicate subsets.code
Example:排序
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3],
[1,3], [2,3], [1,2], [] ]遞歸
用backtrack方法來作, 這道題能夠做爲backtrack最基礎的模板.rem
時間 O(2^n) 一共2^n個解, 每一個解用O(1)
空間 O(n)it
class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } List<Integer> tmp = new ArrayList<>(); dfs(nums, tmp, res, 0); return res; } private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, int index) { res.add(new ArrayList<>(tmp)); for (int i = index; i <nums.length; i++) { tmp.add(nums[i]); dfs(nums, tmp, res, i +1); tmp.remove(tmp.size() -1); } } }
Given a collection of integers that might contain duplicates, nums,
return all possible subsets (the power set).Note: The solution set must not contain duplicate subsets.io
Example:模板
Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2],
[] ]class
用backtrack方法來作, 與I不一樣的是這裏有重複的元素, 因此先將列表排序, 在每次遞歸從index開始的時候, index 和index+1的數重複的話是不容許的由於這樣就會出現[1,2(第一個)] [1,2(第二個)]的狀況. 可是在網下遞歸的時候出現重複是不會有爲題的由於這樣出現的結果是[1,2,2].基礎
時間 O(2^n)
空間 O(n)List
class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> res = new ArrayList<>(); if (nums == null || nums.length == 0) { return res; } Arrays.sort(nums); List<Integer> tmp = new ArrayList<>(); dfs(nums, tmp, res, 0); return res; } private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res, int index) { res.add(new ArrayList<>(tmp)); for (int i = index; i <nums.length; i++) { if (i != index && nums[i] == nums[i-1]) { continue; } tmp.add(nums[i]); dfs(nums, tmp, res, i +1); tmp.remove(tmp.size() -1); } } }