Skip to content

Latest commit

 

History

History
36 lines (32 loc) · 1.06 KB

67. 分割等和子集.md

File metadata and controls

36 lines (32 loc) · 1.06 KB

给你一个只包含正整数的非空数组 nums 。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。

输入:nums = [1,5,11,5] 
输出:true 
解释:数组可以分割成 [1, 5, 5] 和 [11] 。
class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        #dp[ i ][ j ]定义为从数组nums中 0 - i 的元素进行取舍可以得到 j 的方法数量
        n = len(nums)
        allsum = sum(nums)
        if allsum % 2 != 0:
            return False
        target = allsum/2
        dp = [[0]*(target+1) for _ in range(n)]

        dp[0][0] = 1
        for j in range(1,target+1):
            if j == nums[0]:
                dp[0][j] = 1

        for i in range(1,n):
            for j in range(target+1):
                if (j-nums[i]) >= 0:
                    dp[i][j] = dp[i-1][j]+dp[i-1][j-nums[i]]
                else:
                    dp[i][j] = dp[i-1][j]
        return True if dp[-1][-1] else False