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

[LeetCode]416.分割等和子集(C++)

1.代码

class Solution {
public:bool canPartition(vector<int>& nums) {int length = nums.size();int sumn = 0;int maxn = 0;for(int i = 0;i < length;i ++){sumn += nums[i];if(maxn < nums[i]) maxn = nums[i];}if(length < 2 || sumn % 2 == 1){return false;}int o = sumn / 2;if(maxn > o) return false;vector<vector<bool>> result(length,vector<bool>(o+1,false));for(int i = 0;i < length;i ++){result[i][0] = true;}result[0][nums[0]] = true;for(int i = 1;i < length;i ++){for(int j = 1;j <= o;j ++){if(j-nums[i]>=0){if(result[i-1][j-nums[i]] == true) result[i][j] = true;}if(result[i-1][j] == true) result[i][j] = true;}}return result[length-1][o];}
};

2.思路

如果数组长度小于2或存在一个大于总和一半的数或总和是奇数,那么就不存在等和子集。否则,构造一个矩阵记录前i个数中是否存在总和为j的子集。用了动态规划,如果result[i][j]为true,那么result[i-1][j]为true,或者result[i-1][j-nums[i]]为true。


http://www.mrgr.cn/news/13924.html

相关文章:

  • Redis单线程和多线程
  • 【C语言】SQLite 库
  • 【Linux系列】du命令详解
  • 窥一斑而知全豹
  • TCP/IP 协议:互联网的基石
  • 基因生物行业大数据中心之间高效数据备份怎么去实现
  • Linux系统编程:UDP和TCP
  • 数据建模的艺术:SQL中自定义数据类型与表结构的精粹
  • Linux scp命令
  • 给自己复盘用的tjxt笔记day11第二部分
  • 信息学奥赛初赛天天练-75-NOIP2016普及组-完善程序-二分答案、二分查找、贪心算法、贪心策略
  • 阿里云Ubuntu系统安装/简单使用Kafka
  • 优惠券的最佳利用策略:如何在Java代码中优化优惠券的使用
  • 前端技术(五)—— 使用Node.js编写简单的项目
  • docker compose用法详解
  • 【Linux】CodeServer:云IDE部署
  • Linux—— 配置ssl安全证书
  • qml tabbar tabbutton toolbar toolbutton 的区别
  • MDR-SCD-10断链保护器-守护矿山运输安全的智慧卫士
  • 从 MLOps 到 MLOops:揭露机器学习平台的攻击面