二进制法省略,因其不能求长字符串的子集
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);
}
}