题解 | #数组分组#
数组分组
https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
#include <bits/stdc++.h> #include <algorithm> using namespace std; bool divided(vector<int> nums, int target, int index) { if(index == nums.size() && target == 0) { return true; } if(index >= nums.size() && target != 0) { return false; } bool way1 = divided(nums, target-nums[index], index+1); bool way2 = divided(nums, target+nums[index], index+1); return way1||way2; } int main() { int n = 0; cin >> n; vector<int> numsFive; vector<int> numsThree; vector<int> numsNormal; for(int i = 0; i < n; i++) { int numTemp = 0; cin >>numTemp; if(numTemp%5 == 0) { numsFive.push_back(numTemp); } else if(numTemp%3 == 0) { numsThree.push_back(numTemp); } else { numsNormal.push_back(numTemp); } } int sumFive = 0, sumThree = 0; for(int numFive : numsFive) { sumFive += numFive; } for(int numThree : numsThree) { sumThree += numThree; } int target = abs(sumFive-sumThree); bool result = divided(numsNormal, target, 0); if(result) cout << "true" << endl; else cout << "false" << endl; } // 64 位输出请用 printf("%lld")
1.输入时把数据分为3组,5的倍数(第一组),3的倍数(不是5的倍数)(第二组),既不是3的倍数也不是5的倍数(第三组)
2.第三组分成两组使第一组和第二组数值相等,相当于将第三组的数据做“+”或“-”等于第一组与第二组的差值
3.递归做判断