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

18. 4Sum; combination sum

时间:2018-10-03 23:51:40      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:[]   find   reduce   append   dfs   else   rac   sorted   tracking   

18. 4Sum
class Solution(object):
def fourSum(self, nums, target):
nums.sort()
results = []
self.findNsum(nums, target, 4, [], results)
return results

def findNsum(self, nums, target, N, result, results):
if len(nums) < N or N < 2: return

# solve 2-sum
if N == 2:
l,r = 0,len(nums)-1
while l < r:
if nums[l] + nums[r] == target:
results.append(result + [nums[l], nums[r]])
l += 1
r -= 1
while l < r and nums[l] == nums[l - 1]:
l += 1
while r > l and nums[r] == nums[r + 1]:
r -= 1
elif nums[l] + nums[r] < target:
l += 1
else:
r -= 1
else:
for i in range(0, len(nums)-N+1): # careful about range
if target < nums[i]*N or target > nums[-1]*N: # take advantages of sorted list
break
if i == 0 or i > 0 and nums[i-1] != nums[i]: # recursively reduce N
self.findNsum(nums[i+1:], target-nums[i], N-1, result+[nums[i]], results)

combination sum
def combinationSum(candidates, target):
    res = []
    candidates.sort()
    self.dfs(candidates, target, 0, [], res)
    return res

def dfs(self, nums, target, index, path, res):
    if target < 0:
        return  # backtracking
   
if target == 0:
        res.append(path)
        return
    for
i in xrange(index, len(nums)):
        self.dfs(nums, target-nums[i], i, path+[nums[i]], res)

    return result

18. 4Sum; combination sum

标签:[]   find   reduce   append   dfs   else   rac   sorted   tracking   

原文地址:https://www.cnblogs.com/ffeng0312/p/9739056.html

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