Generating all permutations of a given string

前端 未结 30 1625
我寻月下人不归
我寻月下人不归 2020-11-21 06:35

What is an elegant way to find all the permutations of a string. E.g. permutation for ba, would be ba and ab, but what about longer st

30条回答
  •  盖世英雄少女心
    2020-11-21 06:59

    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)

提交回复
热议问题