首页 > 代码库 > 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:

  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.

 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