1. 程式人生 > >leetcode 18. 4Sum

leetcode 18. 4Sum

Given an array nums of n integers and an integer target, are there elements abc, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:

The solution set must not contain duplicate quadruplets.

Example:

Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
  [-1,  0, 0, 1],
  [-2, -1, 1, 2],
  [-2,  0, 0, 2]
]

和之前3 sum一模一樣==

莫名報錯

class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        ans=[]
        nums.sort()
        for i in range(len(nums)):
            if(i!=0 and nums[i]==nums[i-1]):
                continue
            w=i+1
            while (w<len(nums)-2):
                if (nums[w]==nums[w-1] and w!=i+1):# and w<len(nums)-2
                    w=w+1
                    continue
                j=w+1
                k=len(nums)-1
                q=[]
                while(j<k):
                    if(nums[j]+nums[k]+nums[i]+nums[w]>target):
                        k=k-1
                    elif(nums[j]+nums[k]+nums[i]+nums[w]<target):
                        j=j+1
                    else:
                        q=[nums[i],nums[w],nums[j],nums[k]]
                        ans.append(q)
                        while(j<k and nums[j]==nums[j+1]):
                            j=j+1
                        while(j<k and nums[k]==nums[k-1]):
                            k=k-1
                        k=k-1
                        j=j+1
                w=w+1
        return ans