前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >字符串所有排列组合暴力递归

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

作者头像
gzq大数据
发布2021-11-24 13:28:21
5680
发布2021-11-24 13:28:21
举报

给你一个字符串"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;
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2021-11-20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档