DFS和BFS求字符串的所有非空子集———Java

二进制法省略,因其不能求长字符串的子集

1. BFS —— 比DFS高效,推荐


import java.util.*;

public class Main{
    static HashSet<String> set = new HashSet<>();//去重
    static String str;
    static int ans;
    public static void main(String[] args) {
        str = "abca";
        bfs();
        System.out.println(ans);
    }
    public static void bfs(){
        Queue<map> q = new LinkedList<>();
        for(int i = 0;i<str.length();i++){
            if(!set.contains(str.charAt(i)+"")){
                q.offer(new map(str.charAt(i)+"",i));//把所有不重复的字符存入队列
                set.add(str.charAt(i)+"");
                ans++;
            }
        }
        while (!q.isEmpty()){
            map top = q.poll();//poll
            String preStr = top.s;
            int preIndex = top.index;
            for(int i = preIndex+1;i<str.length();i++){
            	if(!set.contains(preStr+str.charAt(i))) {
                    q.offer(new map(preStr+str.charAt(i),i));
                    set.add(preStr+str.charAt(i));
                    ans++;
               	}
            }
        }
    }
}
class map{
    String s;
    int index;
    public map(String s, int index) {
        this.s = s;
        this.index = index;
    }
}

DFS —— 效率极低,稍大点的字符串就跑不动了,不推荐


import java.util.*;

public class Main{
    static HashSet<String> set = new HashSet<>();//去重
    static char[] ch;
    static String pq = "";
    public static void main(String[] args) {
        String s = "abca";
        ch = s.toCharArray();
        dfs(0);
        set.remove("");//注意要除去空集
        System.out.println(set.size());
    }
    public static void dfs(int step){
        if(step == ch.length){//递归结束条件
            set.add(pq);
            return;
        }
        pq += ch[step]+"";//取
        dfs(step+1);
        pq = pq.substring(0,pq.length()-1);//不取
        dfs(step+1);
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Uranus^

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

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

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

打赏作者

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

抵扣说明:

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

余额充值