416. Partition Equal Subset Sum

2018-08-10  本文已影响0人  JERORO_

问题描述

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:
Each of the array element will not exceed 100.
The array size will not exceed 200.

思路

    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if sum(nums) %2 != 0:
            return False
        maximum = sum(nums)//2
        dp = [0]*maximum
        dp.insert(0,1)
        for i in nums:
            for j in range(maximum, i - 1, -1):    #必须从后往前,否则会复用前面的数字
                if dp[j - i]:
                    dp[j] = 1
        return dp[maximum] == 1  
上一篇下一篇

猜你喜欢

热点阅读