A question and may need help


  • 0
    W

    python code

    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            
            return self.helper(sorted(nums), [])
        
        def helper(self, nums, lst):
            if (len(lst) == 3):
                if (sum(lst) == 0):
                    return [lst]
                else:
                    return []
            elif (len(nums) == 0):
                return []
            else:
                withElem = self.helper(nums[1:], lst + [nums[0]]);
                withoutElem = self.helper(nums[1:], lst);
                return withElem + withoutElem
    

    output is [[-1,-1,2],[-1,0,1],[-1,0,1]], 35ms
    my problem is how to make ouput distinct


  • 0
    W
    class Solution(object):
        def threeSum(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            self.output = []
            return self.helper(sorted(nums), [])
        
        def helper(self, nums, lst):
            if (len(lst) == 3):
                if (sum(lst) == 0 and lst not in self.output):
                    self.output += [lst]
                    return [lst]
                else:
                    return []
            elif (len(nums) == 0):
                return []
            else:
                withElem = self.helper(nums[1:], lst + [nums[0]]);
                withoutElem = self.helper(nums[1:], lst);
                return withElem + withoutElem
    

    solution find, but it fails the submission test with very long inputs because of Time Limit Exceeded

    so it may not be good to use recursion for this question?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.