【发布时间】: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