递归版本:
import java.util.Arrays;
public class Matrix {
private static int counter = 0;
private static void combin2(int depth, int[][]matrix, int[] output)
{
int[] row = matrix[depth];
if(depth == 0) {
counter = 0;
output = new int[matrix.length];
System.out.println("matrix length: " + matrix.length);
}
for(int i=0; i<row.length; i++) {
output[depth] = row[i];
if(depth == (matrix.length-1)) {
//print the combination
System.out.println(Arrays.toString(output));
counter++;
} else {
//recursively generate the combination
combin2(depth+1, matrix, output);
}
}
}
public static void main(String[] args) {
int[][] matrix = new int[][] {{1, 2, 3, 4}, {5, 6, 7, 8}};
combin2(0, matrix, null);
System.out.println("counter = " + counter);
System.out.println("");
matrix = new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
combin2(0, matrix, null);
System.out.println("counter = " + counter);
System.out.println("");
matrix = new int[][]{{1, 2, 3}, {4,5,6}, {7,8,9}, {10,11,12}};
combin2(0, matrix, null);
System.out.println("counter = " + counter);
System.out.println("");
}
}
输出:
matrix length: 2
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[2, 5]
[2, 6]
[2, 7]
[2, 8]
[3, 5]
[3, 6]
[3, 7]
[3, 8]
[4, 5]
[4, 6]
[4, 7]
[4, 8]
counter = 16
matrix length: 3
[1, 4, 7]
[1, 4, 8]
[1, 4, 9]
[1, 5, 7]
[1, 5, 8]
[1, 5, 9]
[1, 6, 7]
[1, 6, 8]
[1, 6, 9]
[2, 4, 7]
[2, 4, 8]
[2, 4, 9]
[2, 5, 7]
[2, 5, 8]
[2, 5, 9]
[2, 6, 7]
[2, 6, 8]
[2, 6, 9]
[3, 4, 7]
[3, 4, 8]
[3, 4, 9]
[3, 5, 7]
[3, 5, 8]
[3, 5, 9]
[3, 6, 7]
[3, 6, 8]
[3, 6, 9]
counter = 27
matrix length: 4
[1, 4, 7, 10]
[1, 4, 7, 11]
[1, 4, 7, 12]
[1, 4, 8, 10]
[1, 4, 8, 11]
[1, 4, 8, 12]
[1, 4, 9, 10]
[1, 4, 9, 11]
[1, 4, 9, 12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