Leetcode 416. Partition Equal Subset Sum

时间:2024-10-09 17:06:21

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:

  1. Each of the array element will not exceed 100.
  2. 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.

 class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
s = sum(nums) if s % 2 == 1: return False
target = s/2
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]

注意这L15中的循环必须是反过来的。如果取正向的循环,假设num=3,这个for循环会把所有的dp[3*n]都写成true。这相当于一个数字可以使用任意多次,这并不符合题意。

用类似的方法还可以解决另外一个问题:给定一个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]