【问题标题】:Efficient way to find all permutation of lists [duplicate]查找列表所有排列的有效方法[重复]
【发布时间】:2013-05-18 14:11:33
【问题描述】:

我有一个 Java 列表:

{{1,2},{3,4,5},{6,7,8}}

我试图找到这个列表的所有排列。意思是,在结果中我会得到一个包含下一个的列表:

{{1,3,6},{1,3,7},{1,3,8},{1,4,6}....{2,5,8}}

有没有合理的方法呢?

【问题讨论】:

    标签: java list combinations permutation cartesian-product


    【解决方案1】:

    这里是List<List<Integer> 的实现。

    static public void main(String[] argv) {
        List<List<Integer>> lst = new ArrayList<List<Integer>>();
    
        lst.add(Arrays.asList(1, 2));
        lst.add(Arrays.asList(3, 4, 5));
        lst.add(Arrays.asList(6, 7, 8));
    
        List<List<Integer>> result = null;
    
        result = cartesian(lst);
    
        for (List<Integer> r : result) {
            for (Integer i : r) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
    
    static public List<List<Integer>> cartesian(List<List<Integer>> list) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        int numSets = list.size();
        Integer[] tmpResult = new Integer[numSets];
    
        cartesian(list, 0, tmpResult, result);
    
        return result;
    }
    
    static public void cartesian(List<List<Integer>> list, int n,
                                 Integer[] tmpResult, List<List<Integer>> result) {
        if (n == list.size()) {
            result.add(new ArrayList<Integer>(Arrays.asList(tmpResult)));
            return;
        }
    
        for (Integer i : list.get(n)) {
            tmpResult[n] = i;
            cartesian(list, n + 1, tmpResult, result);
        }
    }
    

    【讨论】:

      【解决方案2】:

      你的意思是这样吗?

      int[] list1 = {1, 2}, list2 = {3, 4, 5}, list3 = {6, 7, 8};
      for (int i : list1) for (int j : list2) for (int k : list2) {
          // something
      }
      

      如果您重视未知数量的列表,最简单的方法可能是递归。

      public void cartesian(int[][] lists) {
          cartesian(lists, new int[lists.length], 0);
      }
      
      public void cartesian(int[][] lists, int[] values, int n) {
          if (n == lists.length) {
              System.out.println(Arrays.toString(values));
          } else {
              for (int i : lists[n]) {
                  values[n] = i;
                  cartesian(lists, values, n + 1);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-23
        • 2014-12-04
        • 2018-11-20
        • 1970-01-01
        相关资源
        最近更新 更多