Python 基礎知識簡單

所有子集的總和

「所有子集之和」問題的詳細指南和 Python 實作。

問題陳述

簡單

寫一個函數 sum_of_all_subsets(arr) ,它接受一個整數陣列並傳回所有可能子集中所有元素的總和。對於包含 n 個元素的數組,每個元素恰好出現在 2^(n-1) 個子集中。所以總和等於 sum(arr) * 2^(n-1)。使用遞歸來計算這個。

約束條件
  • 1 <= len(arr) <= 20
  • -100 <= arr[i] <= 100

範例

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

Subsets: [], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]. Sums: 0+1+2+3+3+4+5+6 = 24. Or: (1+2+3)*2^(3-1) = 6*4 = 24.

Example 2
Input
arr = [5, 10]
Output
30
Explanation

Subsets: [], [5], [10], [5,10]. Sums: 0+5+10+15 = 30. Or: (5+10)*2^1 = 15*2 = 30.

Example 3
Input
arr = [4]
Output
4
Explanation

Subsets: [], [4]. Sums: 0 + 4 = 4. Or: 4 * 2^0 = 4.

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 資源

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