#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int totalSum = 0;
// 检查是否存在和为totalSum / 2的子集
bool hashalf(vector<int> arr, int index, int currentSum) {
if (currentSum == totalSum / 2) {
return true;
}
if (index == arr.size()) {
return false;
}
// 包含当前元素
if (hashalf(arr, index + 1, currentSum + arr[index])) {
return true;
}
// 不包含当前元素
return hashalf(arr, index + 1, currentSum);
}
int main() {
int n;
cin >> n; // 读取数组元素个数
vector<int> arr(n);
for (int i = 0; i < n; i++) {
cin >> arr[i];
totalSum += arr[i]; // 计算总和
}
// 如果总和不能被2整除,则不存在和为totalSum / 2的子集
if (totalSum % 2 != 0) {
cout << "false" << endl;
return 0;
}
// 从第一个元素开始递归查找子集
if (hashalf(arr,0, 0)) {
cout << "true:" << totalSum / 2 << endl;
} else {
cout << "false" << endl;
}
}
将数组分为两个和相等的子集(C++)
最新推荐文章于 2024-06-22 21:53:36 发布