惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
Recent Announcements
Recent Announcements
D
Docker
V
V2EX
阮一峰的网络日志
阮一峰的网络日志
Vercel News
Vercel News
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
U
Unit 42
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
腾讯CDC
B
Blog
博客园_首页
罗磊的独立博客
D
DataBreaches.Net
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
L
LangChain Blog
aimingoo的专栏
aimingoo的专栏
MongoDB | Blog
MongoDB | Blog
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
M
MIT News - Artificial intelligence

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Subsets II | Backtracking
Jaspreet singh · 2026-06-17 · via DEV Community

Jaspreet singh

Problem Statement

Given an integer array nums that may contain duplicates, return all possible subsets (the power set).

The solution must not contain duplicate subsets.


Brute Force Intuition

Generate all possible subsets using the classic Pick / Not Pick recursion.

After generating every subset, store them in a Set to remove duplicates.

While this works, many duplicate subsets are generated unnecessarily and later filtered out.

Complexity

  • Time Complexity: O(2ᴺ × N)
  • Space Complexity: O(2ᴺ)

Brute Force Snippet

Set<List<Integer>> set = new HashSet<>();

generateAllSubsets();

return new ArrayList<>(set);


Moving Towards the Optimal Approach

Notice:

nums = [1,2,2]

After sorting:

[1,2,2]

If we start a subset with the first 2, we should not start another identical subset with the second 2 at the same recursion level.

Instead of generating duplicates and removing them later, we can simply skip duplicate choices while building subsets.


Pattern Recognition

Whenever you see:

  • Generate all subsets
  • Duplicates present
  • Unique combinations required

Think:

Backtracking + Sorting + Duplicate Skipping


Key Observation

After sorting:

1 2 2

At the same recursion level:

if(i != ind && nums[i] == nums[i - 1])
    continue;

This ensures we only consider the first occurrence and skip duplicate starts.


Optimal Java Solution

import java.util.*;

class Solution {

    public List<List<Integer>> subsetsWithDup(int[] nums) {

        Arrays.sort(nums);

        List<List<Integer>> ans = new ArrayList<>();

        helper(0, nums, new ArrayList<>(), ans);

        return ans;
    }

    private void helper(int ind,
                        int[] nums,
                        List<Integer> ds,
                        List<List<Integer>> ans) {

        ans.add(new ArrayList<>(ds));

        for (int i = ind; i < nums.length; i++) {

            if (i != ind && nums[i] == nums[i - 1])
                continue;

            ds.add(nums[i]);

            helper(i + 1, nums, ds, ans);

            ds.remove(ds.size() - 1);
        }
    }
}


Dry Run

Input

nums = [1,2,2]

After Sorting

[1,2,2]

Recursion Tree

[]

├── [1]
│   ├── [1,2]
│   │   └── [1,2,2]
│
├── [2]
│   └── [2,2]
│
└── Skip second 2

Output

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


Why Sorting Helps?

Sorting places duplicates together:

2 2

Now we can easily identify repeated choices and skip them.

Without sorting, duplicate detection becomes much harder.


The Most Important Line

if(i != ind && nums[i] == nums[i - 1])
    continue;

Meaning:

If the current number is the same as the previous number and both belong to the same recursion level, skip it.

This prevents duplicate subsets from being generated.


Complexity Analysis

Metric Complexity
Time Complexity O(2ᴺ × N)
Space Complexity O(N)

Reason:

  • Up to 2ᴺ subsets.
  • Copying subsets takes O(N).
  • Recursion depth is N.

Interview One-Liner

Sort the array and use backtracking. While generating subsets, skip duplicate elements at the same recursion level to avoid duplicate subsets.


Pattern Learned

Generate All Subsets
+
Duplicates Present
+
Unique Answers Needed

=> Sort First
=> Backtracking
=> Skip Duplicates

Similar Problems

  • Subsets II
  • Combination Sum II
  • Permutations II
  • N-Queens Variations
  • Unique Subsequences