LeetCode416: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.

LeetCode:链接

给定一个数组,求能不能把数组分成两部分使得两个子数组的和相等。

先进行数学分析,设子集为A、B,则有sum(A)+sum(B)=sum(nums),sum(A)=sum(B),则有sum(A)=sum(nums)/2。故可以将题目转化为从nums中寻找是否有和为sum(nums)/2的子集,有则返回True,否则返回False

寻找和为sum(nums)/2的子集,可以使用动态规划的思路。用dp[i]来存储和为i的组合个数,对nums里边的数字用n进行遍历,对于所有i>=n的i,有dp[i]=dp[i]+dp[i-n]

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        n = len(nums)
        s = sum(nums)
        if s % 2 != 0:
            return False
        target = s // 2
        dp = [0] * (target+1)
        dp[0] = 1
        for num in nums:
            i = target
            while i >= num:
                dp[i] = dp[i] + dp[i-num]
                i -= 1
        # 组合方法必须大于等于2
        if dp[target] >= 2:
            return True
        else:
            return False

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/85006712