char[] A={'a','b','c','d',...},集合A中,产生所有A的子集{'a'},{'b'},{'a','b'},{'a','b','c'}...这些。
方法一: 根据二进制产生
import java.text.*;

public class SubSet ...{

public static void main(String[] args) ...{
char[] chs = ...{'a', 'b', 'c', 'd'};
int len = 4;
for (int i = 0; i < Math.pow(2,len); i++)
...{
String str = Integer.toBinaryString(i);
int toBinary = Integer.parseInt(str);
DecimalFormat df = new DecimalFormat("0000");
str = df.format(toBinary);
char[] toCharArray = str.toCharArray();
System.out.print("{");
for (int j = 0; j < toCharArray.length; j++)
...{
if (toCharArray[j] == '1')
System.out.print(chs[j] + ",");
}
System.out.println("}");
}
}
}
方法二:
public class PossibleSet 
...{
public static void main(String[] args) 
...{
int[] set = new int[4]; 
char[] chs = ...{'a', 'b', 'c', 'd'};
int i, n, position = 0;
set[position] = 1;
while(true) 
...{
System.out.print("{" + chs[set[0] - 1]); // 第一个数
for(i = 1; i <= position; i++)
System.out.print("," + chs[set[i] - 1]);
System.out.println("}");
if(set[position] < set.length) 
...{ // 递增集合个数
set[position+1] = set[position] + 1;
position++;
}
else if(position != 0) 
...{ // 如果不是第一个位置
position--; // 倒退
set[position]++; // 下一个集合尾数
}
else // 已倒退至第一个位置
break;
}
System.out.println();
}
}


838

被折叠的 条评论
为什么被折叠?



