【问题标题】:Sort Arraylist of Arraylist in java(finding subsets in java)在java中对Arraylist的Arraylist进行排序(在java中查找子集)
【发布时间】:2022-08-23 22:56:28
【问题描述】:

我想找到给定整数数组列表的子集,并将其作为数组列表的数组列表以 java 中的排序顺序返回。

例如:对于 i/p:1 2 3

o/p:

//blank space

1

1 2

1 2 3

1 3

2

2 3

3

而不是作为

1 2 3

1 2

1 3

1

2 3

2

3

感谢您的帮助。

class Solution
{
    public static void subsetsRec(ArrayList<Integer> A, ArrayList<Integer> curr, int ind, ArrayList<ArrayList<Integer>> res) {
        if (ind == A.size()) {
            // System.out.println(curr);
            // res.add(curr);
            res.add(new ArrayList<>(curr));
            return;
        }
    
        curr.add(A.get(ind));
        subsetsRec(A, curr, ind + 1, res);
        curr.remove(curr.size() - 1);
        subsetsRec(A, curr, ind + 1, res);
    }

    public static ArrayList<ArrayList<Integer>> subsets(ArrayList<Integer> A) {
        ArrayList<Integer> curr = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        subsetsRec(A, curr, 0, res);
        return res;
    }
}

    标签: java


    【解决方案1】:

    最简单的方法是将每个内部列表转换为字符串并按词法顺序对其进行排序。

    • 流式传输列表列表
    • 对于每个列表,将每个数字转换为字符串并使用收集器连接。
    • 它们按自然顺序排序,转换为列表。
    List<List<Integer>> list = List.of(List.of(1, 2, 3),
            List.of(1, 2), List.of(1, 3), List.of(1),
            List.of(2, 3), List.of(2), List.of(3));
    
    List<String> result = list.stream()
            .map(lst -> lst.stream().map(i->Integer.toString(i))
                    .collect(Collectors.joining(" ")))
            .sorted(Comparator.naturalOrder()).toList();
    
    result.forEach(System.out::println);
    

    印刷

    1
    1 2
    1 2 3
    1 3
    2
    2 3
    3
    

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2019-10-05
      相关资源
      最近更新 更多