【问题标题】:Count all subsets of an array where the largest number is the sum of the remaining numbers计算数组的所有子集,其中最大数字是剩余数字的总和
【发布时间】:2011-06-15 04:59:52
【问题描述】:

我一直在努力应对 Greplin 挑战的第 3 级。对于那些不熟悉的人,这里有问题:

您必须找到数组的所有子集,其中最大数字是其余数字的总和。例如,对于以下输入:

(1, 2, 3, 4, 6)

子集是

1 + 2 = 3

1 + 3 = 4

2 + 4 = 6

1 + 2 + 3 = 6

这是您应该列出的数字列表 运行你的代码。密码是 子集的数量。在上述情况下 答案是 4。

3、4、9、14、15、19、28、37、47、50、54、56、59、61、70、73、78、81、92、95、97、99

我能够编写一个解决方案,该解决方案构建了 22 个数字的全部 400 万个组合,然后对它们进行了测试,这将为我提供正确的答案。问题是它需要 40 多分钟才能完成。在网上搜索,似乎有几个人能够编写一个算法来在不到一秒钟的时间内得到答案。任何人都可以用伪代码解释比计算昂贵的蛮力方法更好的方法来解决这个问题吗?快把我逼疯了!

【问题讨论】:

  • 您能提供您找到的更快解决方案的链接吗?
  • 这不是作业问题,我也不想在 Greplin 找到工作。只是在寻找比我想出的更好的解决方案。
  • 好的。无论如何,为了鼓励更有效的答案,我只想补充一点,蛮力方法在集合大小的指数时间内运行,或者更准确地说,Theta(2^n),因为有对于任何 n 个元素的集合,恰好是 2^n 个可能的子集。
  • @Cold Hawaiian - 有很多解决方案here,尤其是一个据说可以在 0.2 秒内运行的解决方案here
  • 也许这也应该被标记为组合和算法问题?

标签: algorithm combinatorics computation-theory subset-sum


【解决方案1】:

诀窍是您只需要记录有多少种方法可以做事。由于数字已排序且为正数,因此这很容易。这是一个有效的解决方案。 (在我的笔记本电脑上需要不到 0.03 秒。)

#! /usr/bin/python

numbers = [
    3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56,
    59, 61, 70, 73, 78, 81, 92, 95, 97, 99]

max_number = max(numbers)
counts = {0: 1}
answer = 0
for number in numbers:
    if number in counts:
        answer += counts[number]
    prev = [(s,c) for (s, c) in counts.iteritems()]
    for (s, c) in prev:
        val = s+number;
        if max_number < val:
            continue
        if val not in counts:
            counts[val] = c
        else:
            counts[val] += c
print answer

【讨论】:

  • @Ira Baxter:是的。尝试运行它。我相信大部分时间都花在了启动 Python 上。
  • 那似乎太长了。我已经开始使用 cProfile.run 对我的 Python 进行计时
  • @Ira Baxter:我刚刚使用外部 time 实用程序来计时。
  • 所以这不是一个公平的比较(不幸的是,你不喜欢)但我怀疑你的代码比我的快。
【解决方案2】:

我们知道这些值是非零的,并且从左到右单调增长。

一个想法是枚举可能的总和(任何顺序,从左到右都可以) 然后枚举该值左侧的子集, 因为右边的值不可能参与(他们会做总和 太大)。我们不必实例化集合;就像我们认为的那样 每个值,看看 if 如何影响总和。它可能太大(忽略 该值,不能在集合中),恰到好处(它在集合中的最后一个成员), 或太小,此时它可能会或可能不会在集合中。

[这个问题让我第一次玩 Python。有趣。]

这是 Python 代码;根据 Cprofile.run 这需要 0.00772 秒 在我的 P8700 2.54Ghz 笔记本电脑上。

values = [3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61, 70, 73, 78, 81, 92, 95, 97, 99]

def count():
   # sort(values) # force strictly increasing order
   last_value=-1
   duplicates=0
   totalsets=0
   for sum_value in values: # enumerate sum values
      if last_value==sum_value: duplicates+=1
      last_value=sum_value
      totalsets+=ways_to_sum(sum_value,0) # faster, uses monotonicity of values
   return totalsets-len(values)+duplicates

def ways_to_sum(sum,member_index):
   value=values[member_index]
   if sum<value:
      return 0
   if sum>value:
      return ways_to_sum(sum-value,member_index+1)+ways_to_sum(sum,member_index+1)
   return 1

我得到的结果数是 179。(匹配另一张海报的结果。)

编辑:ways_to_sum 可以使用尾递归循环部分实现:

def ways_to_sum(sum,member_index):
   c=0
   while True:
      value=values[member_index]
      if sum<value: return c
      if sum==value: return c+1
      member_index+=1
      c+=ways_to_sum(sum-value,member_index)

这需要 0.005804 秒才能运行:-} 答案相同。

【讨论】:

  • ++duplicates 不会更改 duplicates 的值。 ++ 不是 Python 中的运算符。 ++duplicates 只是一个表达式,其计算结果为 duplicates。你需要duplicates += 1
  • @WolframH:好的,在您的更改中进行了编辑。需要看看是否有所作为。
【解决方案3】:

这在不到 5 毫秒 (python) 内运行。它使用一种称为记忆递归的动态编程变体。 go 函数计算第一个 p+1 元素的子集数,总和为 target。因为列表已排序,所以为每个元素调用一次函数(如target)并求和结果就足够了:

startTime = datetime.now()
li = [3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61, 70, 73, 78, 81, 92, 95, 97, 99]
memo = {}
def go(p, target):
    if (p, target) not in memo:
        if p == 0:
            if target == li[0]:
                memo[(p,target)] = 1
            else:
                memo[(p,target)] = 0
        else:
            c = 0       
            if li[p] == target: c = 1
            elif li[p] < target: c = go(p-1,target-li[p])
            c += go(p-1, target)
            memo[(p,target)] = c
    return memo[(p,target)]

ans = 0
for p in range(1, len(li)):
    ans += go(p-1, li[p])

print(ans)
print(datetime.now()-startTime)

【讨论】:

  • 它是 memoized 递归,没有被记住 :)
  • 你的运行时是如何计算的?在机器上?
  • 我用时间计算更新了代码。该机器是戴尔笔记本电脑 Intel Core2 Duo CPU T6400 @ 2 Ghz
【解决方案4】:

这行得通

public class A {

  static int[] a = {3,4,9,14,15,19,28,37,47,50,54,56,59,61,70,73,78,81,92,95,97,99};

  public static void main(String[] args) {
    List<Integer> b = new ArrayList<Integer>();

    int count = 0;
    for (int i = 0; i < a.length; i++) {
        System.out.println(b);
        for (Integer t:b) {
        if(a[i]==t)
        {
        System.out.println(a[i]);
            count++;
            }
        }

        int size = b.size();
        for (int j = 0; j < size; j++) {
        if(b.get(j) + a[i] <=99)
            b.add(b.get(j) + a[i]);
        }
            b.add(a[i]);
    }

    System.out.println(count);

  }
}

伪代码(附解释):

  1. 存储以下变量

    i.) 到目前为止的“计数”子集

    ii.)一个包含所有可能子集总和的数组 b

    2.遍历数组(比如 a)。对于每个元素 a[i]

    i.)遍历数组 b 并计算 a[i] 的出现次数。将此添加到“计数”

    ii.)遍历数组 b 并为每个元素 b[j].add (a[i]+b[j]) 到 b 因为这是一个可能的子集和。 (如果a[i]+b[j]> a中的最大元素,你可以忽略添加它)

    iii.)将 a[i] 添加到 b.

3.你有数:)

【讨论】:

  • 您能否解释一下此代码,以便遇到此代码的人知道为什么它有效?
【解决方案5】:

我在这里使用了 Java 中的组合生成器类:

http://www.merriampark.com/comb.htm

遍历组合并查找有效子集的时间不到一秒。 (我不认为使用外部代码符合挑战,但我也没有申请。)

【讨论】:

  • "CombinationGenerator Java 类系统地生成 n 个元素的所有组合,一次取 r 个。"这只是蛮力,在这种情况下会导致指数时间算法......它不可能很好地扩展到更大的问题规模,不是吗?
  • 是的,这是蛮力;不,它不会扩展。它比问题中引用的 40 分钟要快得多。我也希望看到更好的解决方案。
【解决方案6】:
public class Solution {

   public static void main(String arg[]) {
    int[] array = { 3, 4, 9, 14, 15, 19, 28, 37, 47, 50, 54, 56, 59, 61,
        70, 73, 78, 81, 92, 95, 97, 99 };
    int N = array.length;
    System.out.println(N);
    int count = 0;
    for (int i = 1; i < 1 << N; i++) {
        int sum = 0;
        int max = 0;
        for (int j = 0; j < N; j++) {
        if (((i >> j) & 1) == 1) {
            sum += array[j];
            max = array[j];
        }
        }
        if (sum == 2 * max)
        count++;
    }
    System.out.println(count);
    }

    public static boolean isP(int N) {
    for (int i = 3; i <= (int) Math.sqrt(1.0 * N); i++) {
        if (N % i == 0) {
        System.out.println(i);
        // return false;
        }
    }
    return true;
    }
}

希望它有所帮助,但不要只是复制和粘贴。

【讨论】:

  • 这个算法的时间复杂度是:O(N*2^N),所以N不能太大,否则会花很长时间。
【解决方案7】:

我不想打死马,但这里发布的大多数解决方案都错过了优化的关键机会,因此执行时间要长 6 倍。

与其遍历输入数组并搜索与每个值匹配的总和,不如只计算一次所有可能的 RELEVANT 总和,然后查看这些总和中的哪一个出现在原始输入数组中,效率要高得多。 (“相关”总和是任何子集总和

第二种方法的运行速度大约快 6 倍——通常是毫秒而不是厘秒——仅仅是因为它调用递归求和函数的次数大约是原来的 1/6!

这种方法的代码和完整的解释可以在这个 github repo 中找到(它在 PHP 中,因为这是给我这个挑战的人所要求的):

https://github.com/misterrobinson/greplinsubsets

【讨论】:

    猜你喜欢
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 2020-02-02
    • 1970-01-01
    • 2021-10-22
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多