Leetcode 679 Solution

This article provides solution to leetcode question 679 (24-game)

https://leetcode.com/problems/24-game

Solution

class Solution:
    def judgePoint24(self, cards: List[int]) -> bool:
        def dfs(nums):
            if len(nums) == 1:
                return abs(nums[0] - 24) < 0.0000001

            for i, j in itertools.combinations(range(len(nums)), 2):
                new_nums = [num for k, num in enumerate(nums) if k != i and k != j]
                num1 = nums[i]
                num2 = nums[j]

                if dfs(new_nums + [num1 + num2]):
                    return True
                if dfs(new_nums + [num1 - num2]):
                    return True
                if dfs(new_nums + [num2 - num1]):
                    return True
                if dfs(new_nums + [num1 * num2]):
                    return True
                if num2 != 0 and dfs(new_nums + [num1 / num2]):
                    return True
                if num1 != 0 and dfs(new_nums + [num2 / num1]):
                    return True

            return False

        return dfs(cards)