【问题标题】:List of Permutations with repetitions in 2D array二维数组中重复的排列列表
【发布时间】:2017-11-25 02:11:41
【问题描述】:

我有一个问题,列出重复排列,保持这种“风格”,使用递归函数。

例如在二维数组中有 2 个元素,“AB”和“CD”:

Element[0][0] = A; Element[0][1] = B; // AB    
Element[1][0] = C; Element[1][1] = D; // CD

我想通过将 n 个元素(在本例中为 2)重复到 k 个组(在本例中为 2)中来获取所有可能的排列,并将它们保存到一个新的二维数组中 例如在:

Permutation[0][0] = AB; Permutation[0][1] = AB; // 1°: AB,AB
Permutation[1][0] = AB; Permutation[1][1] = CD; // 2°: AB,CD
Permutation[2][0] = CD; Permutation[2][1] = AB; // 3°: CD,AB
Permutation[3][0] = CD; Permutation[3][1] = CD; // 4°: CD,CD

元素和排列必须是二维数组。 我尝试过这种方式,但它仅适用于将 2 个元素排列成 2 个组并且我被锁定:

    int i_perm = 0;
    int i_element = 0;
    int k_tot = 2; // number of groups

    [...]

    calcPerms(2);

    [...]

    private void calcPerms(int k)
    {
        if (k == 0)
        {
            if(i_perm + 1 < i_perm)
                i_perm++;

            i_element=0;
        }
        else
        {
            for (int i = 0; i < element.length; i++)
            {
                Permutation[i_perm][i_element][0] = Element[i][0];
                Permutation[i_perm][i_element][1] = Element[i][1];

                if(i_element + 1 < k_tot)
                    i_element++;

                calcPerms(k - 1);

                if(i_perm >= i_perm)
                    i_perm--;

                Permutation[i_perm][i_element][0] = Element[i][0];
                Permutation[i_perm][i_element][1] = Element[i][1];
                if(i_element + 1 < k_tot)
                    i_element++;
            }
        }
    }

如上所述,这仅适用于 2 个一组中的 2 个元素的排列,并正确返回:

ABAB、ABCD、CDAB、CDCD。

确实,如果我放 3 个元素(第 3 个元素是 EF),它会返回:

ABAB、ABCD、CDEF、EFAB、ABCD、CDEF、EFAB、ABCD、EFEF

代替:

ABAB、ABCD、ABEF、CDAB、CDCD、CDEF、EFAB、EFCD、EFEF

我怎样才能得到我想要的?谢谢大家的帮助,并为我的英语不好表示歉意

【问题讨论】:

  • 一些注意事项:A) 它是“Java”而不是 JAVA。 B)您问题的标签标识了所涉及的语言,因此没有必要将其放在标题中。
  • 对不起!感谢您的建议
  • 没什么大不了的,只是想让这个问题更适合网站格式。

标签: java recursion multidimensional-array permutation repeat


【解决方案1】:

你需要的是Heap's Algorithm

链接的维基百科页面中有明确的伪代码实现。

非递归版本是这样的

procedure generate(n : integer, A : array of any):
    c : array of int

    for i := 0; i < n; i += 1 do
        c[i] := 0
    end for

    output(A)

    i := 0;
    while i < n do
        if  c[i] < i then
            if i is even then
                swap(A[0], A[i])
            else
                swap(A[c[i]], A[i])
            end if
            output(A)
            c[i] += 1
            i := 0
        else
            c[i] := 0
            i += 1
        end if
    end while

【讨论】:

  • 非常好的代码,但对我没有帮助。堆算法是没有重复的排列,例如:ABC、BAC、CAB、ACB、BCA、CBA。我需要重复排列,例如:AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA [...]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 1970-01-01
  • 2016-09-03
  • 2015-07-25
  • 2016-06-07
  • 2014-06-03
  • 1970-01-01
相关资源
最近更新 更多