在java中对Arraylist的Arraylist进行排序(在java中查找子集)



我想找到给定整数arraylist的子集,并在java中按排序顺序将其作为arraylist的arraylist返回。

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

o/p:

//空白

1

12

1 2 3

1 3

2

2 3

3

而不是

1 2 3

12

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;
}
}

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

  • 流式传输列表
  • 对于每个列表,将每个数字转换为字符串,然后使用收集器连接
  • 它们按自然顺序排序,转换为列表
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

最新更新