LeetCode 78. Subsets(子集)

原题网址:https://leetcode.com/problems/subsets/

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

Note:

  • Elements in a subset must be in non-descending order.
  • 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],
  []
]
方法:深度优先搜索。

public class Solution {
    private void find(int[] nums, int pos, int[] subset, int size, int target, List> subsets) {
        if (size == target) {
            List result = new ArrayList<>(target);
            for(int i=0; ipos && nums[i]==nums[i-1]) continue;
            subset[size] = nums[i];
            find(nums, i+1, subset, size+1, target, subsets);
        }
    }
    public List> subsets(int[] nums) {
        Arrays.sort(nums);
        int[] buf = new int[nums.length];
        List> subsets = new ArrayList<>();
        for(int i=0; i<=nums.length; i++) {
            find(nums, 0, buf, 0, i, subsets);
        }
        return subsets;
    }
}

优化:

public class Solution {
    private void find(int[] nums, int pos, int[] subset, int size, List> subsets) {
        List result = new ArrayList<>(size);
        for(int i=0; i> subsets(int[] nums) {
        Arrays.sort(nums);
        int[] buf = new int[nums.length];
        List> subsets = new ArrayList<>();
        find(nums, 0, buf, 0, subsets);
        return subsets;
    }
}


你可能感兴趣的:(组合,幂集,子集,集合,深度优先搜索)