且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

生成特定字符串的所有排列

更新时间:2023-01-11 23:02:56

 公共静态无效的置换(字符串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工作说明: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/