g0001_0100.s0090_subsets_ii.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0001_0100.s0090_subsets_ii;
// #Medium #Array #Bit_Manipulation #Backtracking #Algorithm_II_Day_9_Recursion_Backtracking
// #2022_06_20_Time_2_ms_(82.94%)_Space_43.5_MB_(77.86%)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 90 - Subsets II\.
*
* Medium
*
* Given an integer array `nums` that may contain duplicates, return _all possible subsets (the power set)_.
*
* The solution set **must not** contain duplicate subsets. Return the solution in **any order**.
*
* **Example 1:**
*
* **Input:** nums = [1,2,2]
*
* **Output:** [ [],[1],[1,2],[1,2,2],[2],[2,2]]
*
* **Example 2:**
*
* **Input:** nums = [0]
*
* **Output:** [ [],[0]]
*
* **Constraints:**
*
* * `1 <= nums.length <= 10`
* * `-10 <= nums[i] <= 10`
**/
@SuppressWarnings("java:S5413")
public class Solution {
List> allComb = new ArrayList<>();
List comb = new ArrayList<>();
int[] nums;
public List> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
this.nums = nums;
dfs(0);
allComb.add(new ArrayList<>());
return allComb;
}
private void dfs(int start) {
if (start > nums.length) {
return;
}
for (int i = start; i < nums.length; i++) {
if (i > start && nums[i] == nums[i - 1]) {
continue;
}
comb.add(nums[i]);
allComb.add(new ArrayList<>(comb));
dfs(i + 1);
comb.remove(comb.size() - 1);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy