The*_*ian 6 java recursion permutation
假设我们有一个字母"abcdefghiklimnop".如何以有效的方式以五组为单位递归地重复生成这种字母表的排列?
我几天来一直在努力解决这个问题.任何反馈都会有所帮助.
基本上这与以下内容相同:生成给定字符串的所有排列
但是,我只想要整个字符串的五十个长度的排列.我无法弄明白这一点.
对于"abcdefghiklimnop"长度为5的所有子串,找到子串的排列.例如,如果子字符串是abcdef,我想要它的所有排列,或者如果子字符串是defli,我会想要该子字符串的所有排列.下面的代码给出了字符串的所有排列,但我想用它来查找字符串大小为5的所有子串的所有排列.
public static void permutation(String str) {
permutation("", str);
}
private static void permutation(String prefix, String str) {
int n = str.length();
if (n == 0) System.out.println(prefix);
else {
for (int i = 0; i < n; i++)
permutation(prefix + str.charAt(i), str.substring(0, i) + str.substring(i+1, n));
}
}
Run Code Online (Sandbox Code Playgroud)
为了从递归的字符串中选择五个字符,请遵循一个简单的算法:
这在Java中要短得多:
private static void permutation(char[] perm, int pos, String str) {
if (pos == perm.length) {
System.out.println(new String(perm));
} else {
for (int i = 0 ; i < str.length() ; i++) {
perm[pos] = str.charAt(i);
permutation(perm, pos+1, str);
}
}
}
Run Code Online (Sandbox Code Playgroud)
调用者通过更改以下元素的数量来控制所需的排列长度perm:
char[] perm = new char[5];
permutation(perm, 0, "abcdefghiklimnop");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6212 次 |
| 最近记录: |