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

通过相关的交互式教程、备忘单和代码比较来扩展您的知识。