我正在尝试获取整数数组的链接列表,该列表表示长度为 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;
}
}
}
任何帮助将不胜感激。