1 回答

TA貢獻1865條經驗 獲得超7個贊
雙嵌套循環應該在這里工作。請注意,您要求的輸出實際上是一個 3D 數組(2D 數組的數組):
public int[][] copy2DArray (int[][] input) {
int[][] output = new int[input.length][];
for (int r=0; r < input.length; ++r) {
output[r] = new int[input[r].length];
for (int c=0; c < input[0].length; ++c) {
output[r][c] = input[r][c];
}
}
return output;
}
public static void main(String[] args) {
int [][] a = { {0,1,0},{1,2,1},{1,0,0},{0,2,0} };
int numSwaps = a.length*(a.length-1) / 2;
int[][][] result = new int[numSwaps][][];
int counter = 0;
for (int i=0; i < a.length-1; ++i) {
for (int j=i+1; j < a.length; ++j) {
result[counter] = copy2DArray(a);
int[] temp = result[counter][j];
result[counter][j] = result[counter][i];
result[counter][i] = temp;
++counter;
}
}
System.out.println(Arrays.deepToString(result));
}
這打?。?/p>
[
[[1, 2, 1], [0, 1, 0], [1, 0, 0], [0, 2, 0]],
[[1, 0, 0], [1, 2, 1], [0, 1, 0], [0, 2, 0]],
[[0, 2, 0], [1, 2, 1], [1, 0, 0], [0, 1, 0]],
[[0, 1, 0], [1, 0, 0], [1, 2, 1], [0, 2, 0]],
[[0, 1, 0], [0, 2, 0], [1, 0, 0], [1, 2, 1]],
[[0, 1, 0], [1, 2, 1], [0, 2, 0], [1, 0, 0]]
]
對于某些注釋,我過去使用的策略是使用兩級循環遍歷所有位置交換位置for。對于每個可能的交換,我們首先克隆您的輸入二維a數組。然后,我們在選擇的任何位置交換各個一維數組。最后,我們將該交換數組添加到 3D 結果數組。我們也可以使用類似列表的東西來存儲交換的二維數組。
添加回答
舉報