Split equal and subset python

Author: Cui Yunlong

Date: 2020-10-13

Title description:

Given a non-empty array containing only positive integers. Is it possible to divide this array into two subsets so that the sum of the elements of the two subsets is equal.

note:

The elements in each array will not exceed 100 and
the size of the array will not exceed 200

Example:

Example 1:

Input: [1, 5, 11, 5]

Output: true

Explanation: The array can be divided into [1, 5, 5] and [11].

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: An array cannot be divided into two elements and equal subsets.

Problem solving ideas

x[ i ][ j] = 1
if and only if x[i-1][j]=1 or x[i-1][ j-val[i]] = 1
Perform dynamic programming according to the equation

Code:

class Solution(object):
    def canPartition(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if nums is None:
            return True

        if sum(nums)%2 == 1 or max(nums)>sum(nums)/2:#和为奇数肯定不行 其中有一个大于了一半肯定不行 
            return False
        
        n = len(nums)
        m = sum(nums)
        mid = m/2
        # x[i][j] = 1 当且仅当 x[i-1][j]=1 or x[i-1][ j-val[i] ] = 1
        x = []
        for i in range(n+1):
            row = []
            for j in range(mid+1):
                row.append(0)
            x.append(row)
        
        x[0][0] = 1
        for i in range(1,n+1):
            t = i-1
            for j in range(mid+1):
                if x[t][j] == 1:
                    x[i][j] = 1
                    if j+nums[i-1] < mid:
                        x[i][ j+nums[i-1] ] = 1
                    if j+nums[i-1] == mid:
                        return True
        
        if x[n][mid] == 1:
            return True

        return False

Guess you like

Origin blog.csdn.net/cyl_csdn_1/article/details/109061337