生成特定字符串的所有排列 [英] Generating all permutations of a given string
本文介绍了生成特定字符串的所有排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是优雅的方式来找到一个字符串的所有排列。例如。 BA
,将 BA
和 AB
,但怎么样 ABCDEFGH
?是否有任何的例子Java实现?
解决方案
公共静态无效的置换(字符串str){
置换(,STR);
}
私有静态无效置换(字符串preFIX,字符串str){
INT N = str.length();
如果(N == 0)的System.out.println(preFIX);
其他 {
的for(int i = 0;我n种;我++)
置换(preFIX + str.charAt(i)中,str.substring(0,I)+ str.substring第(i + 1中,n));
}
}
(通过介绍Java编程)
如何在上述code工作说明:<一href="http://www.ericleschinski.com/c/java_permutations_recursion/">ericleschinski.com/c/java_permutations_recursion/
What is an elegant way to find all the permutations of a string. E.g. ba
, would be ba
and ab
, but what about abcdefgh
? Is there any example Java implementation?
解决方案
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));
}
}
(via Introduction to Programming in Java)
Explanation of how the above code works: ericleschinski.com/c/java_permutations_recursion/
这篇关于生成特定字符串的所有排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文