我正在尝试将数组分成N个部分,条件是所有部分至少获得1个数字。
示例:如果将数组[5,10,10,30]分成2(N = 2)个部分,则所有可能的部分组合为:
到目前为止我的代码
public static void main(String[] args) {
int[] a = { 5, 10, 10, 30 };
int maxElement = 3;
int count = 1;
while (count <= maxElement) {
printCombinations(count, a);
count++;
}
}
public static void printCombinations(int count, int[] a) {
System.out.println("start printing");
for (int index = 0; index < count; index++) {
System.out.println(a[index]);
}
System.out.println("----");
for (int index = count; index < a.length; index++) {
System.out.println(a[index]);
}
System.out.println("end printing");
}
它正在按预期打印组合。但是我无法弄清楚如何将其概括为N。感谢您的帮助。
答案 0 :(得分:0)
我不得不将数组转换为ArrayList,以便更轻松地处理数据集。
我使用递归来分离数组的左侧部分,然后递归计算右侧部分。
可能不是最好的代码,但是它可以工作。如果有时间,我会尝试改进变量名。
解释使用List<List<List<Integer>>>
:-
假设输入为
a = { 5, 10, 10, 30 }
n = 2
组合为:-
combination #1: 5 | 10, 10, 30
combination #2: 5, 10 | 10, 30
combination #3: 5, 10, 10 | 30
要存储这3种组合,请使用最外面的List<>
。
第二个List<>
存储每个组合中的部分。因此,组合#1将包含2个部分,[5]和[10,10,30]。
最里面的List<Integer>
用于存储每个节中的整数。因此,组合#1中的#2部分将具有10、10、30的列表。
解决方案
public static void main(String[] args) {
Integer[] a = {5, 10, 10, 30};
final List<List<List<Integer>>> combinations = getCombinations(2, Arrays.asList(a));
for (List<List<Integer>> combination : combinations)
System.out.println(combination);
}
public static List<List<List<Integer>>> getCombinations(int n, List<Integer> a) {
if (n == 1) {
List<List<List<Integer>>> singleLine = new ArrayList<>();
List<List<Integer>> singleSection = new ArrayList<>();
singleSection.add(a);
singleLine.add(singleSection);
return singleLine;
}
List<List<List<Integer>>> res = new ArrayList<>();
if (n > a.size()) return res;
if (n == a.size()) {
List<List<Integer>> sections = new ArrayList<>();
for (Integer e : a) {
List<Integer> l = new ArrayList<>();
l.add(e);
sections.add(l);
}
List<List<List<Integer>>> lines = new ArrayList<>();
lines.add(sections);
return lines;
}
for (int i = 1; i <= a.size() - n + 1; i++) {
List<List<Integer>> left = new ArrayList<>();
List<Integer> leftElements = new ArrayList<>();
left.add(leftElements);
leftElements.addAll(a.subList(0, i));
List<List<List<Integer>>> subResult = getCombinations(n - 1, a.subList(i, a.size()));
for (List<List<Integer>> r : subResult) {
res.add(Stream.concat(left.stream(), r.stream())
.collect(Collectors.toList()));
}
}
return res;
}
输入1
a = {5, 10, 10, 30}
n = 2
输出1
[[5], [10, 10, 30]]
[[5, 10], [10, 30]]
[[5, 10, 10], [30]]
输入2
a = {5, 10, 10, 30}
n = 3
输出2
[[5], [10], [10, 30]]
[[5], [10, 10], [30]]
[[5, 10], [10], [30]]
输入3
a = {5, 10, 10, 30, 40}
n = 3
输出3
[[5], [10], [10, 30, 40]]
[[5], [10, 10], [30, 40]]
[[5], [10, 10, 30], [40]]
[[5, 10], [10], [30, 40]]
[[5, 10], [10, 30], [40]]
[[5, 10, 10], [30], [40]]