题解 | #数组分组#
数组分组
https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86
#include <iostream> using namespace std; #include <vector> #include <list> bool func(const list<int> &nums, list<int>::iterator it, int total3, int total5) { if (it == nums.end() && total3 == total5) { return true; } else if (it != nums.end()) { int temp = *it; it++; if (func(nums, it, total3 + temp, total5) || func(nums, it, total3, total5 + temp)) { return true; } } return false; } int main() { int num, temp; cin >> num; list<int> nums; int total3 = 0; int total5 = 0; for (int i = 0; i < num; i++) { cin >> temp; if (temp % 5 == 0) { total5 += temp; } else if (temp % 3 == 0 && temp % 5 != 0) { total3 += temp; } else { nums.push_back(temp); } } if(func(nums,nums.begin(),total3,total5)){ cout << "true" << endl; } else{ cout << "false" << endl; } }
递归求解,一个数只能加到2组中的任何一组,任何一项递归到true就层层返回即可。
输入处理一下提前分好组就行了
使用list直接用迭代器遍历就行
全部递归完都不行就是false了