将一个数组划分成总和相等的两部分

题目:

判断给定的一个数组,是不是可以分成两个数组之和相等的数组

Example:

[1,2,6,3]可以分成[1,2,3]和[6]

算法:动态规划

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if nums==[]:
            return True
        if sum(nums)%2==1:
            return False
        target = sum(nums)/2
        print target
        dp = [0]*(target+1)
        dp[0] = 1
        for n in nums:
            i = target
            while(i>=n):
                dp[i] = dp[i]+dp[i-n]
                i = i-1
        if dp[target]>=2:
            return True
        else:
            return False


转自:https://blog.csdn.net/xiaoxiaoley/article/details/78980823

你可能感兴趣的:(面试)