【剑指Offer系列】38-字符串的排列(dfs)

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则按字典序打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

思路:dfs
public class Permutation {
    public static void main(String[] args) {
        String s = "abc";
        List<List<String>> res = Lists.newArrayList();
        permutation(res, s.toCharArray(), 0);
        System.out.println(res);//[[abc], [acb], [bac], [bca], [cba], [cab]]
        
        List<String> list = res.stream().flatMap(Collection::stream).collect(Collectors.toList());
        System.out.println(list);//[abc, acb, bac, bca, cba, cab]
    }

    public static void permutation(List<List<String>> result, char[] chars, int index) {
        // 1.终止条件
        // 2.大容器添加小容器
        if (index == chars.length) {
            String s = String.valueOf(chars);
            String[] split = s.replaceAll(" ", "").split(",");
            List<String> path = Arrays.stream(split).filter(str -> !Objects.equals(s, "")).collect(Collectors.toList());
            result.add(path);
            return;
        }
        // 3.循环
        for (int i = index; i < chars.length; i++) {
            // 3.1过滤|去重
            // 3.2优化减支
            // 3.3小容器添加元素(这里使用chars数组本身作为我们的小容器)
            swap(chars, i, index);
            // 3.4递归(横向是bfs,即循环即j++、纵向是dfs,即递归即i++)
            permutation(result, chars, index + 1);
            // 3.5回溯(原本是删除小容器的最后一个元素,这里是将小容器即chars数组还原,因为我们使用它作为小容器进行变化然后添加至大容器,所以作为数组本身还需要回溯回来)
            swap(chars, i, index);
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值