LeetCode
来源:互联网 发布:网络服务器配置与管理 编辑:程序博客网 时间:2024/06/07 17:55
Given a non-empty array containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
Note:
- Each of the array element will not exceed 100.
- The array size will not exceed 200.
Example 1:
Input: [1, 5, 11, 5]Output: trueExplanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]Output: falseExplanation: The array cannot be partitioned into equal sum subsets.
问一个数组能不能划分成和相等的两部分。
可以转化为0/1背包做。先求出数组和,若为奇数,则肯定无法划分,若是偶数sum,则相当于求数组中是否存在子集和 = sum / 2
背包还是两年前跟着连飞学的,居然都过去这么久了,叹气。。。
class Solution {public: bool canPartition(vector<int>& nums) { int sum = 0; for (auto x: nums) sum += x; if (sum & 1) return false; sum >>= 1; vector<int> dp(sum+1, 0); dp[0] = 1; for (auto x: nums) { for (int i = sum; i >= x; --i) { dp[i] += dp[i-x]; } } if (dp[sum]) return true; return false; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- AES加密时的 java.security.InvalidKeyException: Illegal key size 异常
- HTML5本地存储Localstorage实现注册登录以及验证
- 选课(动态规划与DFS在多叉树中的应用)
- Word中如何使公式与文字对齐
- 结构语句
- LeetCode
- java对象序列化
- MyBatis的foreach语句详解
- hdu3265Posters(线段树+离散化+扫描线详解 )
- Dinic 算法模板
- Android进阶之路
- Volley 图片加载相关源码解析
- Android 混淆提示 java.io.FileNotFoundException: ...\proguard
- 英语语法5-现在完成时