Java 二维数组中重复排列的列表
我很难用递归函数列出重复排列,保持这种“风格” 在2D阵列中具有例如2个元素“AB”和“CD”:Java 二维数组中重复排列的列表,java,recursion,multidimensional-array,permutation,repeat,Java,Recursion,Multidimensional Array,Permutation,Repeat,我很难用递归函数列出重复排列,保持这种“风格” 在2D阵列中具有例如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),并将它们保存到一个新的2D数组中 例如: Permutation[0][0] = AB; Permutation[0][1] = AB; // 1°:
Element[0][0] = A; Element[0][1] = B; // AB
Element[1][0] = C; Element[1][1] = D; // CD
我想把n个元素(在本例中为2)重复排列成k个组(在本例中为2),并将它们保存到一个新的2D数组中
例如:
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++;
}
}
}
int i_perm=0;
int i_元素=0;
int k_tot=2;//组数
[...]
calcPerms(2);
[...]
专用无效计算公式(int k)
{
如果(k==0)
{
if(i_perm+1=i_perm)
我烫发--;
置换[i_perm][i_element][0]=元素[i][0];
置换[i_perm][i_元素][1]=元素[i][1];
if(i_元素+1
如上所述,这只适用于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
我怎样才能得到我想要的?谢谢大家的帮助,并为我的英语不好道歉你需要的是
链接的维基百科页面中有一个清晰的伪代码实现
非递归版本如下所示
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
过程生成(n:integer,A:any的数组):
c:int数组
对于i:=0;i
您需要的是
链接的维基百科页面中有一个清晰的伪代码实现
非递归版本如下所示
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
过程生成(n:integer,A:any的数组):
c:int数组
对于i:=0;i
一些注意事项:A)它是“Java”而不是Java。B) 您的问题的标签标识了所涉及的语言,因此没有必要将其放在标题中。对不起!谢谢你的建议没什么大不了的,只是想让这个问题更符合网站的格式。B) 您的问题的标签标识了所涉及的语言,因此没有必要将其放在标题中。对不起!谢谢你的建议没什么大不了的,只是想让这个问题更符合网站的格式。非常好的代码,但对我没有帮助。Heap的算法是无重复的排列,如:ABC、BAC、CAB、ACB、BCA、CBA。我需要重复的排列,比如:aaaab AAC ABB ABC ACA ACB ACC BAA[…]非常好的代码,但对我没有帮助。Heap的算法是无重复的排列,如:ABC、BAC、CAB、ACB、BCA、CBA。我需要重复的排列,比如:AAA AAB AAC ABB ABC ACA ACB ACC BAA[…]