4Sum; Combination Sum

Source: Internet
Author: User

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
Combinationsum (candidates, target):
res = []
Candidates.sort ()
Self.dfs (candidates, target, 0, [], RES)
Res

DFS (self, nums, target, index, PATH, res):
Target < 0:
# backtracking
target = = 0:
Res.append (PATH)
Return
Xrange (index, Len (nums)):
Self.dfs (Nums, target-nums[i], I, path+[nums[i]], RES)

Result

4Sum; Combination Sum

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.