【问题标题】:Efficient algorithm to print all subsets of length k in an array of n elements在 n 个元素的数组中打印所有长度为 k 的子集的高效算法
【发布时间】:2014-07-31 07:35:43
【问题描述】:

这是一个非常经典的问题,我发现的大多数解决方案都使用递归方法,例如this。由于有 Cn,k 组合,我想知道是否存在可以在 O(n*Cn,k) 时间内打印所有组合的算法。我认为链接中给出的答案比这需要更多的时间。此外,是否有一种算法可以在不使用额外空间的情况下打印结果(我的意思是,没有依赖于 n 和 k 的额外空间。O(1) 肯定可以)?

谢谢。

【问题讨论】:

  • 您链接的问题提供了您正在寻找的答案。为什么你认为它是低效的?它不会执行任何不必要的递归。
  • @user1990169:该算法将返回 (current.size()

标签: arrays algorithm set combinations


【解决方案1】:

链接的算法会尽快为您提供所有排列 -- O(n!/k!) -- 这很慢,因为排列的数量呈指数增长。

要在O(Cn,k) 时间内获得所有组合,您可以在回答其他问题时使用其中一种算法:Algorithm to return all combinations of k elements from n

【讨论】:

  • @didierc 为什么是维基百科链接?对不起,我很困惑。
  • 不,没关系,我只是想证明我没有弄乱组合或类似的定义。
【解决方案2】:

只需一个简单的 JavaScript 代码即可从 Windows 命令行 (cscript test.js) 进行测试。

这只不过是一个带有进位的总和,其中“数字”是元素在集合中的位置。

没有递归,只需要存储集合元素和数组来保存当前子集。

// define the initial set
var set = 'abcdefg'.split('');
var setLength = set.length;

// define the subset length and initialize the first subset
var subsetLength = 5;
var aSubset = new Array(subsetLength+1);

var i;
    for( i = 0 ; i < subsetLength ; i++ ) aSubset[i]=i;

// place a guard at the end
    aSubset[subsetLength] = setLength;

// generate each of the posible subsets 
// This is just a sum with carry where the value of each of the "digits" 
// is in the range [i..subset[i+1])
var r = 0, start = 0;
    do {
        // print the subset
        for( i = 0 ; i < subsetLength ; i++ ) {
            WScript.StdOut.Write( set[aSubset[i]] );
        };
        WScript.StdOut.WriteLine('');

        // calculate the next subset
        for( i = start, r = 1 ; i < subsetLength ; i++ ) {
            aSubset[i]++;
            if (aSubset[i] < aSubset[i+1]) { 
                start = ( i==0 ? 0 : i-1 ); 
                r = 0; 
                break; 
            } else { 
                aSubset[i] = i 
            };
        };
    } while (r == 0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2013-01-15
    • 2010-09-12
    相关资源
    最近更新 更多