数字1,2 有组合【1】【2】【1,2】
数字1,2,3 有组合【1】【2】【3】【1,2】,【1,3】,【2,3】,【1,2,3】
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Combination {
public static void combiantion(String[] chs) {
if ((chs == null) || (chs.length == 0)) {
return;
}
List list = new ArrayList();
for (int i = 1; i <= chs.length; i++) {
combine(chs, 0, i, list);
}
}
//从字符数组中第begin个字符开始挑选number个字符加入st中
public static void combine(String[] cs, int begin, int number, Listlist) {
if (number == 0) {
System.out.println(list.toString());
return;
}
if (begin == cs.length) {
return;
}
list.add(cs[begin]);
combine(cs, begin + 1, number - 1, list);
list.remove((String) cs[begin]);
combine(cs, begin + 1, number, list);
}
public static void main(String[] args) {
System.out.println("请输入一个整型数,以获取从1到这个数的所有组合。");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
List list = new ArrayList();
for (int i = 1; i < (n + 1); i++)
list.add(Integer.toString(i));
Object[] obj = list.toArray();
String[] s = new String[obj.length];
for (int i = 0; i < s.length; i++)
s[i] = obj[i].toString();
combiantion(s);
}
}