【问题标题】:Print all the combinations of elements in matrix of size m * n打印大小为 m * n 的矩阵中的所有元素组合
【发布时间】:2015-03-22 04:21:10
【问题描述】:

打印大小为 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();
    }
    }
    
适用于特定输入但不能动态执行..需要帮助..

在此先感谢......

【问题讨论】:

  • 你不能动态执行它是什么意思,但它适用于特定输入?我看到用户在程序开始时输入了行数和列数,那你还想动态化什么?
  • 它适用于上面给定的输入,我在最终逻辑中对 2 的位置进行了一些更改,将其替换为 row ,但随后我给它输入 2*4 矩阵它不起作用....
  • 谢谢。组合的显示顺序重要吗?为了说明我的问题。对于您的预期输出示例,如果元素: 2 、 6 、 7 出现在输出的顶部或中间,它仍然是一个有效的答案吗?
  • 是的,没问题,它应该只打印上述组合......我正在尝试一个通用代码提前谢谢.....

标签: java matrix


【解决方案1】:

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

...
    // 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 存储当前排列并递归更新。

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

【讨论】:

  • 你不必使用递归,这只是一种方式
  • @SergeyPauk 在打印 1 3 5 后我不知道循环是如何工作的......你能提供更多解释......
  • 打印后1 3 5 variablei 加一并变成1 然后你用first[1][2] 更新outputRow 的最后一个元素(之前的值是first[0][2]),这样当前输出行与前一行的不同之处仅在于它的最后一个元素。
  • @SergeyPauk j=2 i=1 Row//j=2 outputRow[2]=7 1 3 7 j=1 i=1 Row//j=1 outputRow[1]=6 j =2 i=0 行//j=2 输出行[2]=5 1 6 5 j=2 i=1 行//j=2 输出行[2]=7 1 6 7 j=0 i=1 行// j=0 outputRow[0]=2 j=1 i=0 Row//j=1 outputRow[1]=3 j=2 i=0 Row//j=2 outputRow[2]=5 2 3 5 j= 2 i=1 行//j=2 输出行[2]=7 2 3 7 j=1 i=1 行//j=1 输出行[1]=6 j=2 i=0 行//j=2 输出行[2]=5 2 6 5 j=2 i=1 Row//j=2 outputRow[2]=7 2 6 7 你能再解释一下 j 的值变为 2 即 j=2 后会发生什么跨度>
  • 它像堆栈...但没有得到 j 的值如何再次变为 1...?请解释一下我很困惑,,,,
【解决方案2】:

这是一种可能的方法

void printCombos(){
    visit(0,-1,"");
}

void visit(int r,int c,String s){
    if(c!=a[0].length-1)
        for(int i=0;i<a.length;i++)
            visit(i,c+1,s+" - "+a[i][c+1]);
    else
        System.out.println(s);
}

将矩阵视为深度访问的树。给定一个虚根 * 这些是边 (*,1) - (*,2) - (1,3) - (1,6) - (2,3) - (2,6) 等等

* --- 1 -- 3 -- 5
  \     \/   \/
   \    /\   /\
    \ 2 -- 6 -- 7

5 和 7 是叶子。

【讨论】:

    【解决方案3】:

    首先再创建一个方法:

    private static void increasePointerArray(int[] poinerArray, int row) 
    {
        for (int i = poinerArray.length-1; i >= 0; i--) {
            if(poinerArray[i] == row-1) {
                continue;
            }
            else {
                poinerArray[i] = poinerArray[i] +1;
                for (int j = i+1; j < poinerArray.length; j++) {
                    poinerArray[j] = 0;
                }
                break;
            }
        }
    }
    

    现在在最后的逻辑部分放下面的代码:

    int[] poinerArray = new int[col];
    int[] MaxArray = new int[col];
    List<int[]> resultList = new ArrayList<int[]>();
    
    Arrays.fill(poinerArray, 0);
    Arrays.fill(MaxArray, row-1);
    
    while(!Arrays.equals(poinerArray, MaxArray)) {
        resultList.add(poinerArray.clone());
        increasePointerArray(poinerArray, row);
    }
    resultList.add(poinerArray.clone());
    
    System.out.println("Printing desired result : ");
    
    for (int[] ks : resultList) {
        StringBuffer sb = new StringBuffer();
        for (j = 0; j < col; j++) {
            sb.append(first[ks[j]][j]+"\t");
        }
        System.out.println(sb.toString());
        sb = null;
    }
    

    【讨论】:

      【解决方案4】:
      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStreamReader;
      import java.util.ArrayList;
      
      public class Permutations{
          public static String strings="";
          public static ArrayList<String> out=new ArrayList<String>();
          public static void gen(ArrayList<ArrayList<String>> x,int index){
              for(int i=0;i<x.size();i++){
                  if(i>0){
                      String[] parts=strings.split(",");
                      strings="";
                      for(int k=0;k<parts.length;k++){
                          if(k==index)
                              break;
                          strings=strings+parts[k]+",";
                      }
                  }
                  if(index==x.get(0).size()-1){
                      strings=strings+(x.get(i).get(index));
                      out.add(strings);
                  }
                  else
                      strings=strings+(x.get(i).get(index))+",";
                  if(index+1<=x.get(0).size()-1)
                      gen(x,index+1);
              }
          }
          public static void main(String[] args) throws IOException{
              ArrayList<ArrayList<String>> x=new ArrayList<ArrayList<String>>();
              BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
              String line;
              while(true){
                  line=br.readLine();
                  if(line.contentEquals("")) break;
                  String[] parts=line.split(" ");
                  x.add(new ArrayList<String>());
                  for(int i=0;i<parts.length;i++){
                      x.get(x.size()-1).add(parts[i]);
                  }
              }
              gen(x,0);
              for(int i=0;i<out.size();i++){
                  System.out.println(out.get(i));
              }
          }
      }
      

      此代码有效。它非常通用且易于理解。我对 2D 数组进行了逐列排列。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-28
        • 2013-02-08
        • 2021-12-31
        • 1970-01-01
        • 2015-07-21
        • 2017-11-26
        • 1970-01-01
        • 2016-04-23
        相关资源
        最近更新 更多