A given non-empty array M is divided into two subsets such that the sum of the elements of the two subsets is equal
Idea: Dynamic programming two subsets, if an element is added to a subset, it means that the other set is missing this element
Input set: 1, 3, 2, 5,1
output result
[[[1, 3, 2], [5, 1]], [[1, 5], [3, 1, 2]]]
/**
* description: 分割一个集合成两个子集和相等
*/
public class TwoCollection {
static LinkedList<LinkedList<LinkedList<Integer>>> linkedList = new LinkedList<>();
public static void main(String[] args) {
// List<Integer> integers = Arrays.asList(1, 5, 11, 5);
List<Integer> integers = Arrays.asList(1, 3, 2, 5,1);
LinkedList<Integer> nums = new LinkedList<>(integers);
LinkedList<Integer> tmp = new LinkedList<>();
LinkedList<Integer> tmp2 = new LinkedList<>(integers);
choose(nums, tmp, tmp2, 0);
System.out.println(linkedList);
}
public static void choose(LinkedList<Integer> nums, LinkedList<Integer> tmp, LinkedList<Integer> tmp2, int start) {
int sum = tmp.stream().mapToInt(o -> o).sum();
int sum1 = tmp2.stream().mapToInt(o -> o).sum();
if (start >= nums.size()) return;
if (sum == sum1) {
LinkedList<LinkedList<Integer>> integers = new LinkedList<>();
integers.add(new LinkedList<>(tmp));
integers.add(new LinkedList<>(tmp2));
linkedList.add(integers);
return;
}
for (int i = start; i < nums.size(); i++) {
tmp.add(nums.get(i));
tmp2.removeFirstOccurrence(nums.get(i));
choose(nums, tmp, tmp2, i + 1);
tmp2.add(tmp.removeLast());
}
}
}