【发布时间】:2016-10-09 19:02:16
【问题描述】:
这个问题是leetcode 416 Partition Equal Subset Sum。
#2 for loop, which got TLE
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
allsum = sum(nums)
if allsum % 2 == 1:
return False
subsets = {() : 0}
temp = dict(subsets)
for each in nums:
for subset in subsets:
new = temp[subset] + each
if new * 2 == allsum:
return True
elif new * 2 < allsum:
temp[tuple(list(subset) + [each])] = new
else:
del temp[subset]
subsets = dict(temp)
return False
DFS + pruning:
class Solution(object):
def canPartition(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
nums.sort()
if sum(nums) % 2 != 0:
return False
else:
target = sum(nums) / 2
return self.path(nums, len(nums), target)
def path(self, nums, length, target):#DFS + pruning
if target == 0:
return True
elif target < 0 or (target > 0 and length == 0):
return False
if self.path(nums, length - 1, target - nums[length - 1]):
return True
return self.path(nums, length - 1, target)
为什么 2 for 循环比 DFS 慢?他们都有剪枝,我认为DFS的时间复杂度,这是一个np问题,应该比2 for循环差,不是吗?
【问题讨论】:
标签: python algorithm loops recursion time-complexity