zoukankan      html  css  js  c++  java
  • Subsets II ——LeetCode

    Given a collection of integers that might contain duplicates, 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,2], a solution is:

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

    题目大意:给定一个数组,返回所有的可能子集合,数组有重复元素,但是子集合不能重复。

    解题思路:这题我首先sort一下,然后遍历,当前元素不是重复的元素就把res里的所有的list取出来加上当前的元素再添加到res里,是重复元素就把上一次加入res的此元素list取出并加上重复元素再放入res。

        public List<List<Integer>> subsetsWithDup(int[] nums) {
            List<List<Integer>> res = new ArrayList<>();
            if (nums == null || nums.length == 0) {
                return res;
            }
            Arrays.sort(nums);
            res.add(new ArrayList<Integer>());
            int lastSize = 0, currSize;
            for (int i = 0; i < nums.length; i++) {
                int start = (i > 0 && nums[i] == nums[i - 1]) ? lastSize : 0;
                currSize = res.size();
                for (int j = start; j < currSize; j++) {
                    List<Integer> tmp = new ArrayList<>(res.get(j));
                    tmp.add(nums[i]);
                    res.add(tmp);
                }
                lastSize = currSize;
            }
            return res;
        }
  • 相关阅读:
    Django与forms组件校验源码
    局部钩子和和全局钩子
    Form组件参数配置
    Form渲染错误信息
    Django与分页器
    Django与from组件
    uiautomatorview 提示:no android devies were detected by adb
    Flutter 应用入门:包管理
    Flutter 应用入门:路由管理
    Flutter 应用入门:计数器
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4470888.html
Copyright © 2011-2022 走看看