Sharing my solution in python

  • 0

    My solution is to reduce the items size until it becomes size of one. Once it is size of one, check if we have reached to '24' or close enough.
    Basically, I tried to pick two elements from the array and apply all the possible computation and recursively call itself with now the array that has the result of computation and the rest.
    As soon as I see True from the call, I return True as well.

    I think I can make my solution cleaner/better but I felt that what I have now may be easier to understand I am posting as is.

    class Solution(object):
        def judgePoint24(self, items):
            :type nums: List[int]
            :rtype: bool
            if len(items) == 1:
                return items[0] == 24 or abs(items[0] - 24.0) <= 0.1
            for i in range(len(items)):
                for j in range(len(items)):
                    if i == j:
                    indexes = set([x for x in range(len(items))])
                    r = []
                    r.append(float(items[i]) + float(items[j]))
                    r.append(float(items[i]) - float(items[j]))
                    r.append(float(items[j]) - float(items[i]))
                    r.append(float(items[i]) * float(items[j]))
                    if items[j] != 0:
                    if items[i] != 0:
                    next_items = [items[idx] for idx in indexes]
                    for x in r:
                        if self.judgePoint24(next_items + [x]) == True:
                            return True
            return False

Log in to reply

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