LeetCode——subsets i-ii

Q: There is now a set of integer no duplicate elements S, S find all subsets
Note:

  • Subset of elements you give must be sorted in non-increasing order
  • Solutions given repeated elements not appear concentrated

For example:
If S = [1,2,3], Solution Set shall be given:
[↵ [. 3], ↵ [. 1], ↵ [2], ↵ [l, 2,3], ↵ [. 1, 3], ↵ [2,3], ↵ [1,2], ↵ [] ↵]

A:

    ArrayList<ArrayList<Integer>> res = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        if (nums.length == 0)
            return res;
        //保证非递增
        Arrays.sort(nums);
        ArrayList<Integer> array = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            //i是这次需要的数量
            DFS(array, i, 0, nums);
        }
        return res;
    }

    private void DFS(ArrayList<Integer> array, int count, int start, int[] nums) {
        if (count < 0)
            return;
        else if (count == 0)
            res.add(new ArrayList<>(array));
        else {
            for (int i = start; i < nums.length; i++) {
                array.add(nums[i]);
                //从当前的下一个开始,count的数量减一,开始的地方加一
                DFS(array, count - 1, i + 1, nums);
                array.remove(array.size() - 1);
            }
        }
    }

Q: an integer of a given element may contain duplicate set S, a subset of the return all sets of integers.
note:

  • Subset element you give in order of non-increasing Yaoan
  • Solutions of concentration given subset can not contain duplicate

For example:
If S = [1,2,2], should be given Solution Set:
[↵ [2], ↵ [. 1], ↵ [1,2,2], ↵ [2,2 &], ↵ [ 1,2], ↵ [] ↵]

A: one more than a determination condition

    ArrayList<ArrayList<Integer>> res = new ArrayList<>();

    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        if (nums.length == 0)
            return res;
        Arrays.sort(nums);
        ArrayList<Integer> array = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            DFS(array, i, 0, nums);
        }
        return res;
    }

    private void DFS(ArrayList<Integer> array, int count, int start, int[] nums) {
        if (count < 0)
            return;
        else if (count == 0)
            res.add(new ArrayList<>(array));
        else {
            for (int i = start; i < nums.length; i++) {
                if (i > start && nums[i] == nums[i - 1])
                    continue;
                array.add(nums[i]);
                DFS(array, count - 1, i + 1, nums);
                array.remove(array.size() - 1);
            }
        }
    }

Guess you like

Origin www.cnblogs.com/xym4869/p/12527402.html