【问题标题】:Efficient method to find permutations of variable number of arrays containing varibale number of elements [duplicate]查找包含可变数量元素的可变数量数组的排列的有效方法[重复]
【发布时间】:2013-01-29 11:40:36
【问题描述】:

可能重复:
How can I find all of the permutations consisting of 1 element from a variable number of arrays of variable length?

假设我有 n 个包含如下元素的数组

 a1 -> e11,e12,e13

 a2 -> e21,e22,e23,e24,e25

 a3 -> e31,e32

 a4 -> e41,e42,e43,e44

 ...

 an -> en1,en2,en3,en4,en5,en6

我想从上面的每个数组中获取包含 n 个元素的所有可能排列。

例如。

 e11,e21,e31,e41.........,en1

 e13,e25,e32,e41.........,en6

等等……

建议我一个有效的方法,如果可能的话,用 Java 或 C 编写代码 sn-p。

【问题讨论】:

  • 我会递归遍历每个组合。这既简单又高效。

标签: java c algorithm permutation combinations


【解决方案1】:

您可以使用以下伪代码:

获取下一个排列的函数:

function NextPermutation(int[] current)
{
    current[0] = current[0] + 1;
    int pointer = 0;
    while(pointer <= n && current[pointer] == limit[pointer])
    {
        current[pointer] = 0;
        pointer = pointer + 1;
        current[pointer] = current[pointer] + 1;
    }
}

预人口代码:

    int[] limit = new int[n + 2];
    int[] current = new int[n + 2];
    limit[1] = a1.length;
    ...
    limit[n] = an.length;

    while(current[n+1] == 0)
    {
        Print(current);
        NextPermutation(current);
    }

current 数组包含数组a1, a2, ... , an 的索引。

【讨论】:

    【解决方案2】:

    由于您对所有数组组合感兴趣,因此 For 循环在这里会很棒 这是一个解决方案(应该修改语法以使其正常工作)

    int i = 0
    int j=0
    int k =0
    
    while(i<arraylength(a1))
    {
    while (j < arraylength(a2))
    {
    //and so  till an
    print a1[i],a2[j];
    j++;
    }
    i++;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-26
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-11
      • 2013-03-09
      • 1970-01-01
      相关资源
      最近更新 更多