题目
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.
Example 1:
Input: [1, 5, 11, 5]
Output: true
Explanation:
The array can be partitioned as [1, 5, 5] and [11].
Example 2:
Input: [1, 2, 3, 5]
Output: false
Explanation:
The array cannot be partitioned into equal sum subsets.
给定一个数组nums(仅包含正整数),将这个数组切分为两个子数组,使得这两个子数组的和相等。若能完成上述切分,返回True,否则返回False
解析
本题思路,先进行数学分析,设子集为A、B,则有sum(A)+sum(B)=sum(nums),sum(A)=sum(B),则有sum(A)=sum(nums)/2。故可以将题目转化为从nums中寻找是否有和为sum(nums)/2的子集,有则返回True,否则返回False。
寻找和为sum(nums)/2的子集,可以使用动态规划的思路。用dp[i]来存储和为i的组合个数,对nums里边的数字用n进行遍历,对于所有i>=n的i,有dp[i]=dp[i]+dp[i-n]。
代码
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
dp = [0]*(target+1)
dp[0] = 1
for n in nums:
i = target
while (i>=n):
dp[i] = dp[i] + dp[i] + dp[i-n]
i -= 1
if dp[target] >= 2:
return True
else:
return False
一刷:2019年04月05日19:47:59
今天天气真好,清明,周五,下午还游了个泳,耶不耶!!!
参考:https://blog.csdn.net/xiaoxiaoley/article/details/78980823