牛客网-递归的使用:输入一个字符串,按字典序打印出该字符串中字符

2020-03-06  本文已影响0人  雨夜微凉886

public class Main {
    public ArrayList<String> permutation(String str) {
        ArrayList<String> list = new ArrayList<>();
        if (str == null || str.length() == 0) {
            return list;
        }
        collect(str.toCharArray(), 0, list);
        Collections.sort(list);
        return list;
    }

    public static void collect(char[] chars, int begin, ArrayList<String> list) {
        if (begin == chars.length - 1) {
            // 不能存入相同的排列
            String s = String.valueOf(chars);
            if (!list.contains(s)) {
                list.add(s);
                return;
            }
        }

        for (int i = begin; i < chars.length; i++) {//大的循环,需要控制第一个逐个和后面的交换
            swap(chars, i, begin);
            collect(chars, begin + 1, list);
            swap(chars, i, begin);
        }

    }

    public static void swap(char[] chars, int i, int j) {
        char temp = chars[j];
        chars[j] = chars[i];
        chars[i] = temp;
    }

    public static void main(String[] args) {
        Main a = new Main();
        System.out.println(a.permutation("abc"));
    }
}
上一篇下一篇

猜你喜欢

热点阅读