解題思路
若第一組總重為 s,另一組為 total-s,差為 |total-2s|。
遞迴對每個蘋果作放入第一組或第二組的二選一,並維護目前第一組總重。
每種分法均被完整枚舉,因此葉節點的最小差就是答案。
時間 O(2^n),遞迴與輸入 O(n);Python 不儲存所有子集合。
Step-by-step animation
教學例子:2、5、8、9 合計 24。
步驟 1 / 3
總重
2、5、8、9 合計 24。
2
5
8
9
- total
- 24
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
vector<long long> a(n);
long long total = 0;
for (auto &x : a) {
cin >> x;
total += x;
}
long long ans = total;
function<void(int, long long)> dfs = [&](int i, long long s) {
if (i == n) {
ans = min(ans, llabs(total - 2 * s));
return;
}
dfs(i + 1, s);
dfs(i + 1, s + a[i]);
};
dfs(0, 0);
cout << ans << '\n';
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。