leetcode(416). Partition Equal Subset Sum
来源:互联网 发布:电子商务erp软件构造 编辑:程序博客网 时间:2024/05/29 08:48
problem
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.
solution
这个问题可以转化为一个0-1背包问题,能否选出若干个数使得它们的和为sum(nums)/2。同时因为是“能否”而不是“最多”,因此可以在存储时使用bool值。
ps:动态规划时使用数组要比dict快,因为dict是接近于
ps1:关于背包问题可以参考背包问题九讲
class Solution(object): def canPartition(self, nums): """ :type nums: List[int] :rtype: bool """ n = len(nums) s = sum(nums) if s % 2: return False else: target = s // 2 d = [[False]*(target+1) for _ in range(n)] for i in range(target+1): d[0][i] = True if i == nums[0] else False for i in range(1, n):#前i个物品 for j in range(target+1):#重量不超过j d[i][j] = d[i-1][j] if j <= nums[i] else (d[i-1][j-nums[i]] or d[i-1][j]) if d[i][target]: return True return d[n-1][target]
阅读全文
0 0
- leetCode No.416 Partition Equal Subset Sum
- LeetCode[416] Partition Equal Subset Sum
- LeetCode 416 Partition Equal Subset Sum
- LeetCode #416: Partition Equal Subset Sum
- LeetCode No.416 Partition Equal Subset Sum
- leetcode 416 c++. Partition Equal Subset Sum
- [Leetcode] #416 Partition Equal Subset Sum
- leetcode(416). Partition Equal Subset Sum
- leetcode-416-Partition Equal Subset Sum
- LeetCode: Partition Equal Subset Sum
- LeetCode: Partition Equal Subset Sum
- [LeetCode]Partition Equal Subset Sum
- [LeetCode] Partition Equal Subset Sum
- Leetcode 416 - Partition Equal Subset Sum(dp)
- Leetcode 416 Partition Equal Subset Sum (算法分析week14)
- Leetcode-416. Partition Equal Subset Sum
- LeetCode—416. Partition Equal Subset Sum
- Leetcode 416. Partition Equal Subset Sum
- Spring Boot 集成 resteasy篇 — jax-rs常用注解介绍
- 干货 | 算法工程师入门第一期——罗恒讲深度学习
- 解析大乐透,预测股票信息入库
- “无人超市”热潮 主要依靠网络技术
- jQuery性能优化
- leetcode(416). Partition Equal Subset Sum
- Two strings HDU
- postgresql修改自增序列
- 溢出文本显示为省略号的效果及其text-overflow:ellipsis;的使用
- 日处理20亿数据_实时用户行为服务系统架构实践
- ECSearch
- Android事件分发机制完全解析,带你从源码的角度彻底理解(下)
- JS格式化long类型的时间
- Resources$NotFoundException