在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("}");
- }
- }
- }
- 运行结果:
- C:java>java SubSet
- {}
- {d,}
- {c,}
- {c,d,}
- {b,}
- {b,d,}
- {b,c,}
- {b,c,d,}
- {a,}
- {a,d,}
- {a,c,}
- {a,c,d,}
- {a,b,}
- {a,b,d,}
- {a,b,c,}
- {a,b,c,d,}
复制代码 二、方法2
- 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();
- }
- }
- 运行结果:
- C:java>java PossibleSet
- {a}
- {a,b}
- {a,b,c}
- {a,b,c,d}
- {a,b,d}
- {a,c}
- {a,c,d}
- {a,d}
- {b}
- {b,c}
- {b,c,d}
- {b,d}
- {c}
- {c,d}
- {d}
复制代码
源码下载:http://file.javaxxz.com/2014/11/5/000235578.zip |