字符串所有排列组合暴力递归

给你一个字符串"acb",可以打印出六种排列组合,这里又是一种index推动的递归,但是这里有一些小trick,就是从第一个开始,在后面的字符串的每一个字符进行交换,这样就可以省很多空间,在数组内原地交换,遍历到每一个字符上也有很多细节,将后面的每一个字符和当前字符进行交换,并且每次遍历完一个,这个字符就不要在动了,随后再还原现场。

     public static void main(String[] args) {
        String input = "abz";
        HashSet<String> res = new HashSet<>();
        printAllPermutation(input, res);
        for (String re : res) {
            System.out.println(re);
        }
    }

    private static void printAllPermutation(String input, HashSet<String> res) {
        char[] sChars = input.toCharArray();
        process(sChars, 0, res);
    }

    private static void process(char[] sChars, int index, HashSet<String> res) {
        if (index == sChars.length) {
            res.add(new String(sChars));
            return;
        }
        
        for (int j = index; j < sChars.length; j++) {
                swap(sChars, index, j);
                process(sChars, index + 1, res);
                swap(sChars, index, j);         
        }
    }

    private static void swap(char[] sChars, int index, int j) {
        char tmp = sChars[index];
        sChars[index] = sChars[j];
        sChars[j] = tmp;
    }

改进:加入缓存,因为每次交换过来的这个字符如果一样的话,后面结果是相同的,没必要再排列了

    public static void main(String[] args) {
        String input = "abz";
        HashSet<String> res = new HashSet<>();
        printAllPermutation(input, res);
        for (String re : res) {
            System.out.println(re);
        }
    }

    private static void printAllPermutation(String input, HashSet<String> res) {
        char[] sChars = input.toCharArray();
        process(sChars, 0, res);
    }

    private static void process(char[] sChars, int index, HashSet<String> res) {
        if (index == sChars.length) {
            res.add(new String(sChars));
            return;
        }
        boolean[] cache = new boolean[26];
        for (int j = index; j < sChars.length; j++) {
            if (!cache[sChars[j] - 'a']) {
                cache[sChars[j] - 'a'] = true;
                swap(sChars, index, j);
                process(sChars, index + 1, res);
                swap(sChars, index, j);
            }
        }
    }

    private static void swap(char[] sChars, int index, int j) {
        char tmp = sChars[index];
        sChars[index] = sChars[j];
        sChars[j] = tmp;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

graceful coding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值