码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 416. Partition Equal Subset Sum

时间:2016-12-03 07:56:10      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:exp   for   elements   tco   turn   range   tar   bool   span   

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:

  1. Each of the array element will not exceed 100.
  2. 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.

本题用DP来解。DP[i]表示是不是存在一个subset使得sum等于i.

 1 class Solution(object):
 2     def canPartition(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: bool
 6         """
 7         s = sum(nums)
 8         
 9         if s % 2 == 1: return False
10         target = s/2
11         dp = [False]*(target+1)
12         dp[0] = True
13         
14         for i in range(len(nums)):
15             for j in range(target, nums[i] - 1, -1):
16                 dp[j] = dp[j] or dp[j - nums[i]]
17         
18         return dp[target]

 

用类似的方法还可以解决另外一个问题:给定一个list of positive integers和一个target. 是否存在一个subset使得sum(subset) = target?

def subsetSum(nums, target):
    s = sum(nums)
    if s < target: return False
    dp = [False] * (target + 1)
    dp[0] = True

    for i in range(len(nums)):
        for j in range(target, nums[i] - 1, -1):
            dp[j] = dp[j] or dp[j - nums[i]]

    return dp[target]

 

Leetcode 416. Partition Equal Subset Sum

标签:exp   for   elements   tco   turn   range   tar   bool   span   

原文地址:http://www.cnblogs.com/lettuan/p/6127905.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!