【发布时间】:2016-05-04 15:48:30
【问题描述】:
所以我正在做一些 Java 练习,最近引起我注意的一个是尝试使用迭代生成 String 的所有排列。网上有很多例子 - 但是,其中很多看起来非常复杂,我无法理解。
我尝试过使用我自己的方法,当使用长度为 3 的字符串进行测试时,它可以正常工作。方法是(对于每个字母)沿着字符串继续移动一个字母,将它与它前面的任何字母交换。例如。
index: 012
string: abc
(iteration 1) swap 'a' (index 0) with letter after it 'b' (index 0+1) : bac
(iteration 2) swap 'a' (index 1) with letter after it 'c' (index 1+1) : bca
(iteration 3) swap 'a' (index 2) with letter after it 'b' (index 0) : acb
current permutations: abc (original), bac, bca, acb
(iteration 3) swap 'b' (index 1) with letter after it 'c' (index 1+1) : acb
(iteration 4) swap 'b' (index 2) with letter after it 'a' (index 0) : bca
(iteration 5) swap 'b' (index 0) with letter after it 'c' (index 1) : cba
current permutations: abc (original), bac, bca, acb, acb, cba
...
这就是我在 Java 中实现它的方式:
String str = "abc"; // string to permute
char[] letters = str.toCharArray(); // split string into char array
int setLength = factorial(letters.length); // amount of permutations = n!
HashSet<String> permutations = new HashSet<String>(); // store permutations in Set to avoid duplicates
permutations.add(str); // add original string to set
// algorithm as described above
for (int i = 0; i < setLength; i++) {
for (int j = 0; j < letters.length; j++) {
int k;
if (j == letters.length - 1) {
k = 0;
} else {
k = j + 1;
}
letters = swap(letters, j, k);
String perm = new String(letters);
permutations.add(perm);
}
}
问题是,如果我输入一个长度为 4 的字符串,我只会得到 12 个排列 (4x3) - 如果我输入一个长度为 5 的字符串,我只会得到 20 个排列 (5x4)。
我可以对该算法进行简单的修改以获得所有可能的排列吗?还是这种特殊方法仅适用于长度为 3 的字符串?
感谢任何反馈!
【问题讨论】:
-
我不确定是否有一种简单的方法可以用你的方法来做到这一点,但你更有可能在 3 号字符串上走运。我建议解决这个问题的是创建某种树,一个包含所有可能性的树
-
迭代往往是 Java 中的最佳解决方案,但是当您需要的循环数量与问题成正比时,递归很可能是最佳解决方案。虽然理论上,您可以使用自己的堆栈将任何递归方法转换为循环,但这通常非常复杂,至少我建议您在尝试之前递归地实现它。
-
您能否提供您的整个 Java 代码以及其他两个函数,这样更易于执行。
标签: java string algorithm iteration permutation