题解 | #数组分组#

数组分组

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了

全部评论

相关推荐

05-07 17:58
门头沟学院 Java
wuwuwuoow:1.简历字体有些怪怪的,用啥写的? 2.Redis 一主二从为什么能解决双写一致性? 3.乐观锁指的是 SQL 层面的库存判断?比如 stock > 0。个人认为这种不算乐观锁,更像是乐观锁的思想,写 SQL 避免不了悲观锁的 4.奖项证书如果不是 ACM,说实话没什么必要写 5.逻辑过期时间为什么能解决缓存击穿问题?逻辑过期指的是什么 其实也没什么多大要改的。海投吧
点赞 评论 收藏
分享
好在哪里了?我请问了?
_hengheng:很好啊,我看旁边同事都入职了都有工作
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务