gpt4 book ai didi

java - 打印大小为 m * n 的矩阵中所有元素的组合

转载 作者:行者123 更新时间:2023-11-30 07:02:18 25 4
gpt4 key购买 nike

打印大小为 m * n 的矩阵中所有元素的组合

示例示例:

1  3  5  
2 6 7

预期输出:

1 , 3 , 5 
1 , 3 , 7
1 , 6 , 5
1 , 6 , 7
2 , 3 , 5
2 , 3 , 7
2 , 6 , 5
2 , 6 , 7

规则:

  • 每个组合都从矩阵的左边开始,然后向右进行。不过它可能会换行。
  • 每个组合的元素数量应等于列数。
  • 组合中同一列中的元素不能出现两次。
  • 列数和行数可能会有所不同。所以解决方案必须是通用的。

    import java.util.Scanner;

    class Combination {
    public static void main(String args[]) {
    int row, col, i, j;

    Scanner in = new Scanner(System.in);
    System.out.println("Enter the number of rows and columns of matrix:\n");
    row = in.nextInt();
    col = in.nextInt();

    int first[][] = new int[row][col];
    System.out.println("Enter the elements if matric m*n:\n");
    for (i = 0; i < row; i++) {
    for (j = 0; j < col; j++) {
    first[i][j] = in.nextInt();
    }
    }
    System.out.println("Matrix:\n");
    for (i = 0; i < row; i++) {
    for (j = 0; j < col; j++) {
    System.out.print(first[i][j] + "\t");
    }
    System.out.println();
    }
    // Final Logic from here...
    System.out.println("\nOut Matrix:\n");
    for (i = 0; i < 2; i++) {
    for (j = 0; j < 2; j++) {
    for (int k = 0; k < 2; k++) {
    System.out.println(first[i][0] + "," + first[j][1] + ","
    + first[k][2]+"\n");
    }
    }
    }
    /* while (i < 2) {
    j = 0;
    while (j < 2) {
    k = 0;
    while (k < 2) {
    System.out.println(first[i][0] + "," + first[j][1] + ","
    + first[k][2]);
    k++;
    }
    j++;
    }
    i++;
    }*/
    in.close();
    }
    }
适用于特定输入但不能动态执行....需要帮助..

提前致谢......

最佳答案

您可以按如下方式使用递归:

...
// Final Logic from here...
System.out.println("\nOut Matrix:\n");
int[] outputRow = new int[col];
print(0, row, col, first, outputRow);

}

private static void print(int j, int row, int col, int[][] first, int[] outputRow) {
for (int i = 0; i < row; i++) {
outputRow[j] = first[i][j];
// recursively continue to populate outputRow until we reach the last column (j == col -1)
if (j < col - 1) {
print(j + 1, row, col, first, outputRow);
}
// we have reached the last column (j == col -1) so now we could print current permutation
if (j == col - 1) {
for (int k = 0; k < col; k++) {
System.out.print(" " + outputRow[k]);
}
System.out.println();
}
}
}

在这里,我们处理每个以 j==0 开头的递归调用。

outputRow 存储当前排列并递归更新。

当我们递归地到达最后一列时,就该打印当前排列了。

关于java - 打印大小为 m * n 的矩阵中所有元素的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29190960/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com