import java.util.HashSet;
//status:状态码,二进制表示,其位数==输入字符串的长度,用于标记新字符串中已包含的字符
public class Main {
public static void main(String[] args) {//调试方法
HashSet<String> hs=UpSet("abcd");
for (String s : hs) {
System.out.println(s);
}
}
public static HashSet<String> UpSet(String s) {
HashSet result=new HashSet<String>();
UpSet(s, 0, new StringBuilder(), result);
return result;
}
private static void UpSet(String s,int status,StringBuilder pre,HashSet<String> result) {
int length = s.length();
if (status == (1 << (length)) - 1) {//新字符串中已包含原字符串中所有字符
result.add(pre.toString());//将新字符串加入集合
return;
}
for (int i = 0; i < length; i++) {//将原字符串中各个位置的字符按照不同顺序加入到新字符串中
int now=1<<i;
if ((status&now)!=0)continue;//判断当前位置字符是否已包含在新字符串中
StringBuilder current = new StringBuilder(pre);
current.append(s.charAt(i));
UpSet(s, (status ^ now), current, result);
}
}
}