Python Nozioni di baseFacile

Generate subsets

Guida dettagliata e implementazione Python per il problema 'Genera sottoinsiemi'.

Dichiarazione del problema

Facile

Scrivi una funzione generate_subsets(arr) che prenda un elenco di interi distinti e restituisca tutti i possibili sottoinsiemi (il set di potenza). Restituisce il risultato come un elenco ordinato di elenchi ordinati. Includere il sottoinsieme vuoto. Ordina ogni singolo sottoinsieme, quindi ordina l'elenco dei sottoinsiemi prima per lunghezza, poi lessicograficamente.

Vincoli
  • 0 <= len(arr) <= 10
  • All elements in arr are distinct
  • -100 <= arr[i] <= 100

Esempi

Example 1
Input
arr = [1, 2, 3]
Output
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]
Explanation

An array of 3 elements has 2^3 = 8 subsets, including the empty set and the full set.

Example 2
Input
arr = [1, 2]
Output
[[], [1], [2], [1, 2]]
Explanation

2^2 = 4 subsets.

Example 3
Input
arr = [5]
Output
[[], [5]]
Explanation

2^1 = 2 subsets: the empty set and [5].

Need a Hint?
Prendi in considerazione l'utilizzo di strutture dati specifiche della ricorsione come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Apri nell'editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.