我班上有以下代码:
public static ArrayList<String[]> allCombos;
public static void main(String[] args){
allCombos = new ArrayList<String[]>();
String[] arr = {"A","B","C","D","E","F"};
combinations(arr, 3, 0, new String[3]);
}
static void combinations(String[] arr, int len, int startPosition, String[] result){
if (len == 0){
allCombos.add(result); // this is where the problem seems to be
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations(arr, len-1, i+1, result);
}
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,每次allCombos.add(result)调用时combinations(),该方法似乎将整个数组中的每个元素设置为结果的当前值,从而超过前一次迭代combinations()设置最近添加的allCombosas的值.如果allCombos …