Generating all permutations of a given string

前端 未结 30 1680
我寻月下人不归
我寻月下人不归 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-21 06:50

    Use recursion.

    when the input is an empty string the only permutation is an empty string.Try for each of the letters in the string by making it as the first letter and then find all the permutations of the remaining letters using a recursive call.

    import java.util.ArrayList;
    import java.util.List;
    
    class Permutation {
        private static List permutation(String prefix, String str) {
            List permutations = new ArrayList<>();
            int n = str.length();
            if (n == 0) {
                permutations.add(prefix);
            } else {
                for (int i = 0; i < n; i++) {
                    permutations.addAll(permutation(prefix + str.charAt(i), str.substring(i + 1, n) + str.substring(0, i)));
                }
            }
            return permutations;
        }
    
        public static void main(String[] args) {
            List perms = permutation("", "abcd");
    
            String[] array = new String[perms.size()];
            for (int i = 0; i < perms.size(); i++) {
                array[i] = perms.get(i);
            }
    
            int x = array.length;
    
            for (final String anArray : array) {
                System.out.println(anArray);
            }
        }
    }
    

提交回复
热议问题