Generating all permutations of a given string(JAVA)

来源:互联网 发布:实用数据再分析法 pdf 编辑:程序博客网 时间:2024/06/01 21:23


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?

The answer below is obviously elegant!


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));    }}
Reference: http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string
1 0
原创粉丝点击