我正在尝试获取一个整数数组的链表,表示长度为N的位字符串的可能排列,例如对于N = 2
00 01 10 11
我已经成功地编写了代表位作为字符串的代码,如下:
public static LinkedList<String> printBin(String soFar, int iterations) {
if(iterations == 0) {
LinkedList<String> ret = new LinkedList<String>();
ret.add(soFar);
return ret;
}else {
LinkedList<String> ret = new LinkedList<String>();
ret.addAll(printBin(soFar + "0", iterations - 1));
ret.addAll(printBin(soFar + "1", iterations - 1));
return ret;
}
}
然而,我尝试将此代码转换为适用于整数数组,因此当N = 2时,我得到:
11 11 11 11
以下是SSCE:
public class Main {
public static void main(String[] args){
int numberOfBits = 2;
LinkedList<int []> results = printBin(new int[numberOfBits], 0, numberOfBits);
Iterator<int[]> i = results.iterator();
while(i.hasNext()){
int[] temp = i.next();
for(int j = 0; j < temp.length; j++){
System.out.print(temp[j]);
}
System.out.println("");
}
}
public static LinkedList<int[]> printBin(int[] soFar, int counter, int iterations) {
if(iterations == 0) {
LinkedList<int[]> ret = new LinkedList<int[]>();
ret.add(soFar);
return ret;
}else {
LinkedList<int[]> ret = new LinkedList<int[]>();
int[] soFar1 = soFar; soFar1[counter] = 0;
int[] soFar2 = soFar; soFar2[counter] = 1;
ret.addAll(printBin(soFar1, counter + 1, iterations - 1));
ret.addAll(printBin(soFar2, counter + 1, iterations - 1));
return ret;
}
}
任何帮助都将不胜感激。