Generating all permutations of a given string

前端 未结 30 1627
我寻月下人不归
我寻月下人不归 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:50

    Here is a straightforward minimalist recursive solution in Java:

    public static ArrayList permutations(String s) {
        ArrayList out = new ArrayList();
        if (s.length() == 1) {
            out.add(s);
            return out;
        }
        char first = s.charAt(0);
        String rest = s.substring(1);
        for (String permutation : permutations(rest)) {
            out.addAll(insertAtAllPositions(first, permutation));
        }
        return out;
    }
    public static ArrayList insertAtAllPositions(char ch, String s) {
        ArrayList out = new ArrayList();
        for (int i = 0; i <= s.length(); ++i) {
            String inserted = s.substring(0, i) + ch + s.substring(i);
            out.add(inserted);
        }
        return out;
    }
    

提交回复
热议问题