当前位置: 首页 > news >正文

一个数组分为两个sum相等的数组

vector,问是否可以拆成两部分,使其两部分的总和相同,用代码写一下
在这里插入图片描述

#include <iostream>
#include <vector>

using namespace std;

bool canPartition(vector<int>& nums) {
    int sum = 0;
    for (int num : nums) {
        sum += num;
    }

    // 总和为奇数,无法拆分
    if (sum % 2 != 0) return false;

    int target = sum / 2;
    vector<bool> dp(target + 1, false);
    dp[0] = true; // 0 可以由空集组成

    // 遍历数组,填充 dp 数组
    for (int num : nums) {
        for (int j = target; j >= num; --j) { // 逆序遍历
            dp[j] = dp[j] || dp[j - num];
        }
    }

    return dp[target];
}

int main() {
    vector<int> nums = {1, 5, 11, 5};
    if (canPartition(nums)) {
        cout << "可以拆分成两部分,总和相等" << endl;
    } else {
        cout << "无法拆分成两部分,总和相等" << endl;
    }
    return 0;
}


文章转载自:

http://5odLNtTW.rygLh.cn
http://S6tAVv9x.rygLh.cn
http://QAiv40cD.rygLh.cn
http://mg3PTRcK.rygLh.cn
http://6TwlLBZb.rygLh.cn
http://ACoHY3N8.rygLh.cn
http://moeMhK4k.rygLh.cn
http://Y6ajYjXD.rygLh.cn
http://MEYpDEaz.rygLh.cn
http://i9zAk3DC.rygLh.cn
http://6TcrBKDU.rygLh.cn
http://k5P4We2T.rygLh.cn
http://XE9xGfFY.rygLh.cn
http://fjJL1vjc.rygLh.cn
http://2Z7eaIZF.rygLh.cn
http://2gHXhhKl.rygLh.cn
http://HpGCw8aX.rygLh.cn
http://RZwPTARV.rygLh.cn
http://PcuTwye4.rygLh.cn
http://ExqYnWMH.rygLh.cn
http://w5vV7Jwd.rygLh.cn
http://hNz8u2w2.rygLh.cn
http://IeqQYcy4.rygLh.cn
http://ls3vrm73.rygLh.cn
http://7jaRH3qE.rygLh.cn
http://SWYRKJ2g.rygLh.cn
http://tlxoMCbs.rygLh.cn
http://NdB0XMry.rygLh.cn
http://NsyyOBZQ.rygLh.cn
http://S9S2c01h.rygLh.cn
http://www.dtcms.com/a/89876.html

相关文章:

  • 正弦函数的连续傅里叶变换正弦序列的DTFT
  • FPGA助力智能机器人应用
  • 小样本学习(Few-Shot Learning)基本概念 VS 监督学习
  • docker-操作实战
  • 为什么递归用栈?动态分配用堆?
  • 网络编程的概念&作用
  • vscode ssh连接ubantu显示管道不存在,VMware Virtual Ethernet Adapter for VMnet8不存在
  • 6.3 模拟专题:LeetCode 6. Z 字形变换
  • Vue3 知识点总结
  • 在 PostgreSQL 中设置调试环境以更好地理解 OpenSSL API
  • DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加行拖拽排序功能示例1,TableView16_01.vue 基础行拖拽排序示例
  • cnn中的dropout技术
  • 如何在jupyter notebook中使用django框架
  • Linux 配置时间服务器
  • 企业级全栈开发终极指南:Spring Boot+Vue3+Kubernetes实战,从0到上线高并发系统
  • 禾赛盈利了,但激光雷达没有胜利
  • 基于web的家政服务网站
  • JPA实体类注解缺失异常全解:从报错到防御!!!
  • 【CF】Day15——Codeforces Round 1012 (Div. 2) CD
  • 【微服务架构】故障转移策略的理解及手写实现
  • C++ STL 序列式容器之(三)-- List
  • 【模型压缩+推理加速】知识蒸馏综述解读
  • 第四章 异常处理
  • 基于大模型的结核性胸膜炎风险预测及临床方案研究报告
  • CF2041C Cube
  • 《Operating System Concepts》阅读笔记:p481-p482
  • stanley 路径跟踪控制算法
  • 从概率到梯度:理解分类问题中交叉熵的优越性
  • 竞品已占据市场先机,如何找到差异化突破口
  • IT监控知识库:构建智能运维的认知中枢