Leetcode 416. Partition Equal Subset Sum

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 416. Partition Equal Subset Sum

LeetCode 416. Partition Equal Subset Sum

[动态规划] leetcode 416 Partition Equal Subset Sum

[LeetCode] 416 Partition Equal Subset Sum

leetcode 416. Partition Equal Subset Sum 分割等和子集(中等)

(Java) LeetCode 416. Partition Equal Subset Sum —— 分割等和子集