Patrón Subconjuntos y Conjuntos Potencia

Domina el patrón Subset & Power Set con backtracking: genera subconjuntos en Java, plantilla universal, ejemplos y variaciones (duplicados, tamaño k) y aplicaciones en IA y desarrollo de software a medida.

2 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Backtracking o retroceso es especialmente potente cuando debemos explorar todos los subconjuntos o combinaciones de elementos. En este Blog 2 Subset & Power Set Pattern aprenderás un patrón universal que se reutiliza en entrevistas técnicas y en proyectos reales de desarrollo de aplicaciones a medida y software a medida.

Definición del problema. Dado un conjunto de elementos, genera todos los subconjuntos el power set.

Ejemplo. Entrada [1, 2, 3]. Salida [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]]

Intuición. Cada elemento tiene dos opciones incluirlo o excluirlo. Estas decisiones forman un árbol binario de profundidad n que produce 2^n subconjuntos.

Plantilla universal para subconjuntos con backtracking en estilo Java.

void backtrack int index, List<Integer> current, int[] nums, List<List<Integer>> results { if index == nums.length { results.add new ArrayList<> current ; return; } backtrack index + 1, current, nums, results; current.add nums[index]; backtrack index + 1, current, nums, results; current.remove current.size() - 1; }

Implementación Java sencilla para el power set.

import java.util.*; public class SubsetsPattern { public List<List<Integer>> subsets int[] nums { List<List<Integer>> results = new ArrayList<>(); backtrack 0, new ArrayList<>(), nums, results; return results; } private void backtrack int index, List<Integer> current, int[] nums, List<List<Integer>> results { if index == nums.length { results.add new ArrayList<> current ; return; } backtrack index + 1, current, nums, results; current.add nums[index]; backtrack index + 1, current, nums, results; current.remove current.size() - 1; } }

Visualización del árbol de recursión para la entrada [1,2].

[] -> decisiones incluir excluir rama izquierda excluye 1 y luego decide sobre 2 rama derecha incluye 1 y luego decide sobre 2 Resultado final hojas [], [2], [1], [1,2]

Variaciones frecuentes en entrevistas.

1 Subconjuntos con duplicados. Entrada [1,2,2]. Objetivo evitar subconjuntos duplicados. Estrategia ordenar y saltar duplicados contiguos.

private void backtrackDup int start, List<Integer> current, int[] nums, List<List<Integer>> results { results.add new ArrayList<> current ; for int i = start; i < nums.length; i++ { if i > start && nums[i] == nums[i - 1] continue; current.add nums[i]; backtrackDup i + 1, current, nums, results; current.remove current.size() - 1; } }

2 Subconjuntos de tamaño k. Entrada nums=[1,2,3], k=2. Salida [[1,2], [1,3], [2,3]].

private void backtrackK int start, int k, List<Integer> current, int[] nums, List<List<Integer>> results { if current.size() == k { results.add new ArrayList<> current ; return; } for int i = start; i < nums.length; i++ { current.add nums[i]; backtrackK i + 1, k, current, nums, results; current.remove current.size() - 1; } }

3 Subconjuntos de una cadena. Entrada abc. Salida vacio, a, b, c, ab, ac, bc, abc. Misma lógica, usando caracteres en lugar de enteros.

Complejidad. Tiempo O 2^n para enumerar todos los subconjuntos. Espacio O n por la profundidad de recursión más el almacenamiento del resultado.

Conclusiones clave. Los problemas de subconjuntos se resuelven con el patrón incluir excluir. En arrays con duplicados, ordena y salta duplicados. Para subconjuntos de tamaño fijo, añade una condición de tamaño. Este patrón es base para combinaciones, particionado, decisiones y generación de estados en agentes IA.

Que sigue. En el Blog 3 Permutation Pattern veremos cómo generar todas las permutaciones con y sin duplicados, una extensión natural del patrón de backtracking.

Sobre Q2BSTUDIO. Somos una empresa de desarrollo de software y aplicaciones a medida, especialistas en inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y power bi, automatización de procesos y agentes IA para empresas. Si buscas llevar este tipo de patrones a productos reales, nuestro equipo crea plataformas y productos escalables con buenas prácticas, pruebas automatizadas y seguridad integrada.

Si necesitas transformar una idea en producto digital, descubre cómo abordamos proyectos de software a medida y aplicaciones a medida en desarrollo de aplicaciones y software multiplataforma. Para potenciar tus procesos con modelos de ia para empresas, copilotos internos y agentes IA, visita nuestra oferta en inteligencia artificial.

También te ayudamos a desplegar soluciones seguras y elásticas en servicios cloud aws y azure, a robustecer tu postura de ciberseguridad y pentesting, y a convertir datos en decisiones con power bi y business intelligence, alineando analítica avanzada con objetivos de negocio.

Palabras clave recomendadas para tu estrategia técnica y de negocio. aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.