【问题标题】:Searching for subsets (interesting complex task)搜索子集(有趣的复杂任务)
【发布时间】:2010-10-10 20:57:55
【问题描述】:

我一直在做Greplin programming challenge,并进入了最后的关卡,任务听起来是这样的:

For the final task, you must find all subsets of an array
where the largest number is the sum of the remaining numbers.
For example, for an input of:

(1, 2, 3, 4, 6)

the subsets would be

1 + 2 = 3
1 + 3 = 4
2 + 4 = 6
1 + 2 + 3 = 6

Here is the list of numbers (3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61, 70, 73, 78, 81, 92, 95, 97, 99) 
you should run your code on.
The password is the number of subsets.  In the above case the
answer would be 4.

你能给我一个建议,我应该在这里做什么?我认为蛮力不适合这里,是吗?

不要写代码!

谢谢。

【问题讨论】:

    标签: java php task


    【解决方案1】:

    使用dynamic programming,可以将较小数字的解决方案扩展到较大数字的解决方案。

    【讨论】:

      【解决方案2】:

      我蛮力解决了这个问题(在 Python 中),不到一分钟就得到了答案。 Python library itertools 支持生成数组/列表/序列的 N 长度组合。

      要生成数组的所有可能子集,首先生成可能的 1 长度子集,然后生成 2 长度子集,然后生成 3 长度子集,直到 N 长度。如果没有一个好的库来提供combinations() 函数供您使用,那么在自己编写代码时,一种可能的方法是使用递归。

      【讨论】:

      • 要枚举子集,您可以只计算从 0 到 2^n-1 的二进制数。最低的 n 位确定集合成员。
      猜你喜欢
      • 1970-01-01
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      相关资源
      最近更新 更多