Python Two Sum - Brute Force Approach

后端 未结 5 734
谎友^
谎友^ 2021-01-14 06:04

I\'m new to Python and have just started to try out LeetCode to build my chops. On this classic question my code misses a test case.

The problem is as follows:

5条回答
  •  無奈伤痛
    2021-01-14 06:59

    import itertools
    
    class Solution:
        def twoSum(self, nums, target):
            subsets = []
            for L in range(0, len(nums)+1):
                for subset in itertools.combinations(nums, L):
                    if len(subset)!=0:
                        subsets.append(subset)
            print(subsets) #returns all the posible combinations as tuples, note not permutations!
            #sums all the tuples
            sums = [sum(tup) for tup in subsets]
            indexes = []
            #Checks sum of all the posible combinations
            if target in sums:
                i = sums.index(target)
                matching_combination = subsets[i] #gets the option
                for number in matching_combination:
                    indexes.append(nums.index(number))
                return indexes
            else:
                return None
    
    
    test_case = Solution()    
    array = [1,2,3]
    print(test_case.twoSum(array, 4))
    

    I was trying your example for my own learning. I am happy with what I found. I used the itertools to make all the combination of the numbers for me. Then I used list manipulation to sum all the possible combination of numbers in your input array, then I just check in one shot if the target is inside the sum array or not. If not then return None, return the indexes otherwise. Please note that this approach will return all the three indexes as well, if they add up to the target. Sorry it took so long :)

提交回复
热议问题