有一个数字集合,希望把这个集合中的所有组合情况都列举出来,不知道有什么算法?有没有现成的代码?如:{1,2,3,4}集合,结果应列举:{1},{1,2},{1,3},{1,4},{2,3},{2,4},{3,4},{1,2,3},{1,2,4}……{1,2,3,4},真是太费劲了,我就简单的列举一部分,说实话我自己想都挺费劲的,更别说实现了,求助哪位高人帮忙解决一下,不胜感激!谢谢!
调试欢乐多
select * from a,b
public class Test {
public static void main(String []args){
new Test().run();
}
public void run(){
int startNum = 1;
int endNum = 4;
for(int i = startNum ; i <= endNum; i ++){
String tempStr = "{ " + i + ",";
printStr(tempStr);
int tempI = i;
goOn(++ tempI, endNum, tempStr);
}
}
public void goOn(int start, int end, String str){
for(int i = start; i <= end; i ++){
String temp = str;
temp += " " + i + ",";
printStr(temp);
int tempI = i;
goOn(++ tempI, end, temp);
}
}
public void printStr(String str){
str = str.substring(0, str.length() -1) + "}";
System.out.println(str);
}
}
//console
//{ 1}
//{ 1, 2}
//{ 1, 2, 3}
//{ 1, 2, 3, 4}
//{ 1, 2, 4}
//{ 1, 3}
//{ 1, 3, 4}
//{ 1, 4}
//{ 2}
//{ 2, 3}
//{ 2, 3, 4}
//{ 2, 4}
//{ 3}
//{ 3, 4}
//{ 4}应该解决了楼主的问题了.
public class Test {
int [] array = {1, 2, 3, 4, 8, 10};
public static void main(String []args){
new Test().run();
}
public void run(){
int startNum = 0;
int endNum = array.length;
for(int i = startNum ; i < endNum; i ++){
String tempStr = "{ " + array[i] + ",";
printStr(tempStr);
int tempI = i;
goOn(++ tempI, endNum, tempStr);
}
}
public void goOn(int start, int end, String str){
for(int i = start; i < end; i ++){
String temp = str;
temp += " " + array[i] + ",";
printStr(temp);
int tempI = i;
goOn(++ tempI, end, temp);
}
}
public void printStr(String str){
str = str.substring(0, str.length() -1) + "}";
System.out.println(str);
}
}
//console
//{ 1}
//{ 1, 2}
//{ 1, 2, 3}
//{ 1, 2, 3, 4}
//{ 1, 2, 3, 4, 8}
//{ 1, 2, 3, 4, 8, 10}
//{ 1, 2, 3, 4, 10}
//{ 1, 2, 3, 8}
//{ 1, 2, 3, 8, 10}
//{ 1, 2, 3, 10}
//{ 1, 2, 4}
//{ 1, 2, 4, 8}
//{ 1, 2, 4, 8, 10}
//{ 1, 2, 4, 10}
//{ 1, 2, 8}
//{ 1, 2, 8, 10}
//{ 1, 2, 10}
//{ 1, 3}
//{ 1, 3, 4}
//{ 1, 3, 4, 8}
//{ 1, 3, 4, 8, 10}
//{ 1, 3, 4, 10}
//{ 1, 3, 8}
//{ 1, 3, 8, 10}
//{ 1, 3, 10}
//{ 1, 4}
//{ 1, 4, 8}
//{ 1, 4, 8, 10}
//{ 1, 4, 10}
//{ 1, 8}
//{ 1, 8, 10}
//{ 1, 10}
//{ 2}
//{ 2, 3}
//{ 2, 3, 4}
//{ 2, 3, 4, 8}
//{ 2, 3, 4, 8, 10}
//{ 2, 3, 4, 10}
//{ 2, 3, 8}
//{ 2, 3, 8, 10}
//{ 2, 3, 10}
//{ 2, 4}
//{ 2, 4, 8}
//{ 2, 4, 8, 10}
//{ 2, 4, 10}
//{ 2, 8}
//{ 2, 8, 10}
//{ 2, 10}
//{ 3}
//{ 3, 4}
//{ 3, 4, 8}
//{ 3, 4, 8, 10}
//{ 3, 4, 10}
//{ 3, 8}
//{ 3, 8, 10}
//{ 3, 10}
//{ 4}
//{ 4, 8}
//{ 4, 8, 10}
//{ 4, 10}
//{ 8}
//{ 8, 10}
//{ 10}
public static void main(String[] args) {
final int[] numSet = {1,2,3,4};
long max = 1<<numSet.length;
for (int i = 1; i < max; i++) {
for (int j = 0; j < numSet.length; j++) {
if ((i&(1<<j))!=0) {
System.out.print(numSet[j] + ", ");
}
}
System.out.println();
}
}
}