From 0178d88bce0e150297a1cbcd8278db2b5dae8b9f Mon Sep 17 00:00:00 2001 From: huangge1199 Date: Fri, 20 Aug 2021 13:43:31 +0800 Subject: [PATCH] =?UTF-8?q?90:=E5=AD=90=E9=9B=86=20II?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/leetcode/editor/cn/SubsetsIi.java | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 src/main/java/leetcode/editor/cn/SubsetsIi.java diff --git a/src/main/java/leetcode/editor/cn/SubsetsIi.java b/src/main/java/leetcode/editor/cn/SubsetsIi.java new file mode 100644 index 0000000..c0e151c --- /dev/null +++ b/src/main/java/leetcode/editor/cn/SubsetsIi.java @@ -0,0 +1,76 @@ +//给你一个整数数组 nums ,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。 +// +// 解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。 +// +// +// +// +// +// 示例 1: +// +// +//输入:nums = [1,2,2] +//输出:[[],[1],[1,2],[1,2,2],[2],[2,2]] +// +// +// 示例 2: +// +// +//输入:nums = [0] +//输出:[[],[0]] +// +// +// +// +// 提示: +// +// +// 1 <= nums.length <= 10 +// -10 <= nums[i] <= 10 +// +// +// +// Related Topics 位运算 数组 回溯 👍 630 👎 0 + +package leetcode.editor.cn; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +//90:子集 II +class SubsetsIi { + public static void main(String[] args) { + //测试代码 + Solution solution = new SubsetsIi().new Solution(); + } + + //力扣代码 + //leetcode submit region begin(Prohibit modification and deletion) + class Solution { + public List> subsetsWithDup(int[] nums) { + Arrays.sort(nums); + List> result = new ArrayList<>(); + dfs(nums,0,new ArrayList<>(),result,new ArrayList<>()); + return result; + } + + private void dfs(int[] nums, int index, List list, List> result, List use) { + if (index == nums.length) { + List temp = new ArrayList<>(list); + String key = Arrays.toString(temp.toArray()); + if (!use.contains(key)) { + result.add(temp); + use.add(key); + } + return; + } + list.add(nums[index]); + dfs(nums, index + 1, list, result, use); + list.remove(list.size() - 1); + dfs(nums, index + 1, list, result, use); + } + } +//leetcode submit region end(Prohibit modification and deletion) + +} \ No newline at end of file