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:
- Each element in the array will not exceed 100
- 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:
, before the number represents n, and if you can find digital combination of C, as can
True
, 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.
- 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:
- Border: 0 boundary 。
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]