DFS-字符串切割的所有可能

题目:给出"abc",给出所有可能的切分组合

example1:[a, b, c]、[a,bc]、[ab,c]、[abc]
example2:给出aab : 所有切割后的组合形式[a,a,b]、[aa,b]、[a,ab]、[aab]

/**
 * Author:m
 * Date: 2023/04/11 22:42
 */
public class SplitABC {
    public static void main(String[] args) {
        String candidate = "abc";
        List<List<String>> res = dfs(candidate);
        System.out.println(res);
    }

    private static List<List<String>> dfs(String candidate) {
        List<List<String>> result = Lists.newArrayList();
        if (StringUtils.isBlank(candidate)) {
            return result;
        }

        List<String> combine = Lists.newArrayList();
        int startIndex = 0;
        recursion(result, combine, candidate, startIndex);
        return result;
    }

    private static void recursion(List<List<String>> result, List<String> combine, String candidate, int startIndex) {
        // 1.终止条件
        // 2.小集合添加至大集合
        if (startIndex == candidate.length()) {
            result.add(Lists.newArrayList(combine));
        }

        // 3.循环
        for (int i = startIndex; i < candidate.length(); i++) {
            String subStr = candidate.substring(startIndex, i + 1);
            // 3.1 去重|过滤
            // 3.2优化
            // 3.3添加元素至小集合
            combine.add(subStr);
            // 3.4递归(i+1)
            recursion(result, combine, candidate, i + 1);
            // 3.5回溯(删除小集合中最后一个元素)
            combine.remove(combine.size() - 1);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值