Leetcode-416. Segmentation and subsets

Article Directory

Title Description

Given a non-empty array contains only positive integer. Whether this array may be divided into two subsets, so that the two sets of sub-elements and equal.

note:

  1. Each element in the array will not exceed 100
  2. Size of the array does not exceed 200

Example 1:

Input: [1, 5, 11, 5]

Output: true

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

Example 2:

Input: [1, 2, 3, 5]

Output: false

Explanation: the array elements and is not divided into two equal subsets.

analysis

This question may in fact turn out to be 0-1 knapsack problem using dynamic programming to do problems:

  • Status means: F ( n , C ) F(n,C) , before the number represents n, and if you can find digital combination of C, as canTrue, can notFalse.
    • If the n-th element is not considered, then the situation is equal to the situation prior to the n-1 element, i.e. F ( n 1 , C ) F(n-1,C)
    • If the n-th element considered, the situation before the subset is equal to the n-1 element and n-th element of plus and can be composed and C, C-nums [n] denotes the n-1 before the element can be composed and to C-nums [n], then the n-th element coupled nums [n], and to C, it may constitute a subset.
  • State transition formula: F ( n , C ) = F ( n 1 , C )    o r    F ( n 1 , C n u m s ( i ) ) F(n,C)=F(n−1,C) ~~or~~ F(n−1,C−nums(i))
  • Border: 0 boundary F a l s e False

Code

class Solution:
    def canPartition(self, nums: List[int]) -> bool:
        sumNums = sum(nums)
        
        if sumNums%2==1:
            return False

        sumOfHalf = sumNums//2


        length = len(nums)
        dp = [[False for i in range(sumOfHalf+1)] for j in range(length+1)]
        for i in range(length+1):
            dp[i][0] = True

        for i in range(1, length+1):
            for j in range(1, int(sumOfHalf)+1):
                dp[i][j] = dp[i-1][j]
                if j>=nums[i-1]:
                    dp[i][j] = dp[i][j] or dp[i-1][j-nums[i-1]]
        
        return dp[length][sumOfHalf]
Published 219 original articles · won praise 85 · Views 140,000 +

Guess you like

Origin blog.csdn.net/z_feng12489/article/details/103526528