Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

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

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

Tips:

  1. recursion 方法注意for循环里面, helper是i+1,比较难想;还有for里面i是从depth开始不是0!!
  2. 大神方法就是注意各种new, 各种添加;O(n^2)
  3. 位运算很精妙,建议找机会听个讲座if ((i & (1 << j)) != 0)
  4. 记得一定要result.add(new ArrayList), 要new, 要new!

Code:

recursive:

public class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        if (nums == null || nums.length == 0) {
            return result;
        }
        Arrays.sort(nums);
        dfs(nums, result, new ArrayList<Integer>(), 0);
        return result;
    }
    private void dfs(int[] nums, List<List<Integer>> result, List<Integer> path, int depth) {
        result.add(new ArrayList<Integer>(path));
        for (int i = depth; i < nums.length; i++) {
            path.add(nums[i]);
            dfs(nums, result, path, i + 1);
            path.remove(path.size() - 1);
        }
    }
}

大神插入法:

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        result.add(new ArrayList<Integer>());
        for (int i = 0; i < nums.length; i++) {
            List<List<Integer>> newRes = new ArrayList<>(result); 
            for (List<Integer> l : result) {
                ArrayList<Integer> newList = new ArrayList<>(l);
                newList.add(nums[i]);
                newRes.add(newList);
            }
            result = newRes;
        }
        return result;
    }
}

位运算:

class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        int n = nums.length;
        Arrays.sort(nums);
        result.add(new ArrayList<Integer>());
        for (int i = 1; i < (1 << n); i++) {
            ArrayList<Integer> subset = new ArrayList<Integer>();
            for (int j = 0; j < n; j++) {
                if ((i & (1 << j)) != 0) {
                    subset.add(nums[j]);
                }
            }
            result.add(subset);
        }
        return result;
    }
}

results matching ""

    No results matching ""