我正在尝试编写一个函数,以便给定 n 个字符串,它生成所有 n P 2
对此类字符串。例如,如果我有 [ab, bc, bd]
,它将生成 [[ab, bc], [bc, ab], [ab, bd], [bd, ab], [bc, bd], [bd, bc]]
,不一定按这个顺序。我有一个困惑的递归函数来执行此操作,
private static void permutation(ArrayList<String> names, int pos, String[] pair, ArrayList<ArrayList<String>> out) {
if (pos == names.size()) {
if(!names.get(0).equals(names.get(1))){
out.add(new ArrayList<String>(Arrays.asList(names.get(0), names.get(1))));
}
} else {
for (int i = 0 ; i < pair.length ; i++) {
names.add(pair[i]);
permutation(names, pos+1, pair, out);
}
}
}
但是当字符串超过 6 个时,这会生成 stackoverflow 错误
。谁能帮忙为此编写一个迭代方法?
最佳答案
你不需要递归函数;两个嵌套循环就可以了。
基本上,循环 i from 0 to n-1
获取该对的第一个元素;然后再次循环,循环j from 0 to n-1, where i<>j
,并取对 (i,j)
。 (显然,将所有此类对放入 out
集合中。)
关于java - 在Java中迭代生成所有置换字符串对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338570/