問題描述
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.
思路
- 能被partition說明
nums
的總和是偶數;并且總和的一半,稱為maximum
,就是partition過后,每一半的總和 - 運用動態規劃,創建一個數組
dp
,記錄從0
到maximum
間,每個數字是否能被其余數字加出來
對于nums
中的每個數字i
,從后往前循環一遍dp中的數字j
,范圍是maximum
到i
如果j-i
存在,則說明j
值可以被湊出來,在dp中記錄1
最后返回dp[maximum]==1
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