我正在尝试编写一个程序,它将迭代字符串数组的所有可能排列,并返回包含所有排列的二维数组。具体来说,我尝试使用长度为 4 的字符串数组返回 24 行 4 列的 2D 数组。
我只找到了迭代打印字符串的方法,但没有在数组中使用它们。我还找到了递归方法,但它们不起作用,因为我与其他人一起使用此代码,并且递归函数要困难得多。
对于我想要代码执行的操作,我知道标题应该是:
public class Permutation
{
public String[][] arrayPermutation(String[] str)
{
//code to return 2D array
}
}
//我尝试使用堆算法的递归方法,但是//它的参数非常复杂。
我对编程非常陌生,任何帮助将不胜感激。
最佳答案
您的排列问题基本上只是一个索引排列问题。 如果您可以对从 0 到 n - 1 的所有可能变化的数字进行排序,则可以将它们用作输入数组的索引,并简单地复制字符串。下面的算法不是最优的,但它足够图形化,可以迭代地解释和实现。
public static String[][] getAllPermutations(String[] str) {
LinkedList<Integer> current = new LinkedList<>();
LinkedList<Integer[]> permutations = new LinkedList<>();
int length = str.length;
current.add(-1);
while (!current.isEmpty()) {
// increment from the last position.
int position = Integer.MAX_VALUE;
position = getNextUnused(current, current.pop() + 1);
while (position >= length && !current.isEmpty()) {
position = getNextUnused(current, current.pop() + 1);
}
if (position < length) {
current.push(position);
} else {
break;
}
// fill with all available indexes.
while (current.size() < length) {
// find first unused index.
int unused = getNextUnused(current, 0);
current.push(unused);
}
// record result row.
permutations.add(current.toArray(new Integer[0]));
}
// select the right String, based on the index-permutation done before.
int numPermutations = permutations.size();
String[][] result = new String[numPermutations][length];
for (int i = 0; i < numPermutations; ++i) {
Integer[] indexes = permutations.get(i);
String[] row = new String[length];
for (int d = 0; d < length; ++d) {
row[d] = str[indexes[d]];
}
result[i] = row;
}
return result;
}
public static int getNextUnused(LinkedList<Integer> used, Integer current) {
int unused = current != null ? current : 0;
while (used.contains(unused)) {
++unused;
}
return unused;
}
getAllPermutations 方法被组织在初始化部分、收集所有排列(数字)的循环中,最后将找到的索引排列转换为字符串排列。
由于从 int 到 String 的转换很简单,我只解释集合部分。循环迭代的时间与表示未完全耗尽或从内部终止的时间一样长。
首先,我们增加表示形式(当前
)。为此,我们采用最后一个“数字”并将其增加到下一个自由值。然后,如果我们超过长度,我们弹出,并查看下一个数字(并递增它)。我们继续此操作,直到达到合法值(低于长度的一个)。
之后,我们用所有剩余的数字填充剩余的数字。完成后,我们将当前表示存储到数组列表中。
该算法在运行时方面并不是最优的!堆速度更快。但是迭代地实现堆需要一个不平凡的堆栈,这实现/解释起来很烦人。
关于java - 如何将所有数组排列迭代返回为二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56631234/