Python 基礎知識簡單

生成子集

「產生子集」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 generate_subsets(arr) ,它接受不同整數的列表並傳回所有可能的子集(冪集)。將結果作為已排序清單的已排序清單傳回。包括空子集。對每個單獨的子集進行排序,然後首先按長度對子集列表進行排序,然後按字典順序排序。

約束條件
  • 0 <= len(arr) <= 10
  • All elements in arr are distinct
  • -100 <= arr[i] <= 100

範例

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?
考慮使用特定於遞歸的資料結構,例如集合或堆。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

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

在編輯器中開啟
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

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。