Subsets I

Given a set of distinct integers, nums, return all possible subsets
(the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3],
[1,3], [2,3], [1,2], [] ]

思路

用backtrack方法来做, 这道题可以作为backtrack最基础的模板.

复杂度

时间 O(2^n) 一共2^n个解, 每个解用O(1)
空间 O(n)

代码

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);
        }
    }
}

Subsets II

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.

Example:

Input: [1,2,2] Output: [ [2], [1], [1,2,2], [2,2], [1,2],
[] ]

思路

用backtrack方法来做, 与I不同的是这里有重复的元素, 所以先将列表排序, 在每次递归从index开始的时候, index 和index+1的数重复的话是不允许的因为这样就会出现[1,2(第一个)] [1,2(第二个)]的情况. 但是在网下递归的时候出现重复是不会有为题的因为这样出现的结果是[1,2,2].

复杂度

时间 O(2^n)
空间 O(n)

代码

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);
        }
    }
}

lpy1990
26 声望10 粉丝