问题:给定一个有限集,试列出其幂集中的所有元素。
解决方法1:To generate all subsets of S,list all 2n bit strings of length n(for instence, in increasing order),and write down the corresponding subsets.
解决方法2:以集合<a,b,c,d>为例
第一步: 添加空集,
第二步: 添加单元素成为单元素子集,并且将它存入tempBefore字符串数组做为转换成两元素子集时使用,temp中单元素子集为a,b,c,d。
第三步: 用第二步生成的tempBefore和集合S,对每个子集添加一个元素,生成n+1元素子集。
1 private static int change(String[] tempAfter, String[] tempBefore, 2 String[] first) { 3 int tempAfterLength = 0; 4 for (int i = 0; !tempBefore[i].equals("#"); i++) { 5 tempAfterLength = addTempAfter(tempAfter, tempBefore[i], first, 6 tempAfterLength); 7 } 8 return tempAfterLength; 9 }
private static int addTempAfter(String[] tempAfter, String string, String[] first, int tempAfterLength) { int location = getLastStringLocation(first, string); if (first[location + 1].equals("#")) { return tempAfterLength; /** * 示例如下,如果tempBefore[i]为d!ef 而输入串集合为"v,<a,v>,d,ef#" * 那么我们可以知道通过子集d!ef已经不能再生成新的子集了 * */ } for (int i = location + 1; !first[i].equals("#"); i++) { tempAfter[tempAfterLength] = string + "!" + first[i]; tempAfterLength++; } return tempAfterLength; }
/**
* 得到字符串String中最后一个元素在输入集合中的位置 例如输入集合为"v,<a,v>,d,ef#",String 为v!d
* 则返回位置为2,因为元素d在first数组中的下标为2 其中的str为取的String中最后一个 本例中取的是d
* */
private static int getLastStringLocation(String[] first2, String string) {
String str = "";
int i = 0, location = 0;
for (int j = 0; j < string.length(); j++) {
str = str + string.charAt(j);
if (string.charAt(j) == ‘!‘) {
str = "";
}
}
for (i = 0; !first2[i].equals("#"); i++) {
if (first2[i].equals(str)) {
location = i;
}
}
return location;
}
原文:http://www.cnblogs.com/GUET-edu-cn/p/5137117.html