首页 > 代码库 > Leetcode 416. Partition Equal Subset Sum
Leetcode 416. Partition Equal Subset Sum
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: true Explanation: The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5] Output: false Explanation: The array cannot be partitioned into equal sum subsets.
本题用DP来解。DP[i]表示是不是存在一个subset使得sum等于i.
1 class Solution(object): 2 def canPartition(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: bool 6 """ 7 s = sum(nums) 8 9 if s % 2 == 1: return False 10 target = s/2 11 dp = [False]*(target+1) 12 dp[0] = True 13 14 for i in range(len(nums)): 15 for j in range(target, nums[i] - 1, -1): 16 dp[j] = dp[j] or dp[j - nums[i]] 17 18 return dp[target]
用类似的方法还可以解决另外一个问题:给定一个list of positive integers和一个target. 是否存在一个subset使得sum(subset) = target?
def subsetSum(nums, target): s = sum(nums) if s < target: return False dp = [False] * (target + 1) dp[0] = True for i in range(len(nums)): for j in range(target, nums[i] - 1, -1): dp[j] = dp[j] or dp[j - nums[i]] return dp[target]
Leetcode 416. Partition Equal Subset Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。