一种是用Stack的方法,我是参考网上一个牛人的算法实现的。
另外一种,理解起来就容易好多。如:ABCD
其实就是1111(16进制)进行-1的操作,直到变成0000为止。每次减一时,将得到的数为1的值输出。如1111-1 = 1110,就是ABC的意思。
现在大家分别来看一下这两种代码怎样实现他们的思想吧.
第一种 :
package test;
import java.util.Stack;
public class Combination {
public static char[] array = {'A', 'B', 'C'};
private static Stack<Character> stack = new Stack<Character>();
public static void combination(int index) {
if (index > array.length-1) return;
stack.push(array[index]);
print(stack);
combination(index + 1);
stack.pop();
combination(index + 1);
}
public static void print(Stack<Character> stack) {
for (Character i : stack) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] args) {
combination(0);
}
}
第二种:
package test;
public class Person {
public static void main(String[] s) {
char[] array = {'A', 'B', 'C'};
int n = array.length;
int total = (int) Math.pow(2, n);
for (int i = 1; i < total; i++) {
String result = "";
for (int j = 0; j < n; j++) {
if (((i >> j) % 2) == 1) {
result += array[j];
}
System.out.print(result);
result = "";
}
System.out.println();
}
}
}