码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]739. 24 Game/[Leetcode]679. 24 Game

时间:2019-07-15 22:40:24      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:als   lan   ann   eal   numbers   tput   car   ever   oge   

?[Lintcode]739. 24 Game/[Leetcode]679. 24 Game

本题难度: Hard/Medium

Description

You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through?*,?/,?+,?-,?(,?)?to get the value of 24.

Example 1:

Input: [4, 1, 8, 7]
Output: True
Explanation: (8-4) * (7-1) = 24

Example 2:

Input: [1, 2, 1, 2]
Output: False

Note:

The division operator?/?represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
Every operation done is between two numbers. In particular, we cannot use?-?as a unary operator. For example, with?[1, 1, 1, 1]?as input, the expression?-1 - 1 - 1 - 1?is not allowed.
You cannot concatenate numbers together. For example, if the input is?[1, 2, 1, 2], we cannot write this as 12 + 12.

我的代码


import sys
class Solution:
? ??
? ? def judgePoint24(self, nums: List[int]) -> bool:
? ? ? ? def cal(a,b):
? ? ? ? ? ? if a == 0:
? ? ? ? ? ? ? ? return b,-b,0
? ? ? ? ? ? if b == 0:
? ? ? ? ? ? ? ? return a,-a,0
? ? ? ? ? ? return list({a+b,a-b,b-a,a*b,a/b,b/a})
? ? ? ? stack = [[float(item) for item in nums]]
? ? ? ? while (len(stack) > 0):
? ? ? ? ? ? tmp_nums = stack.pop()
? ? ? ? ? ? if len(tmp_nums) == 1:
? ? ? ? ? ? ? ? if abs(tmp_nums[0] - 24.0) <= 0.0001:
? ? ? ? ? ? ? ? ? ? return True
? ? ? ? ? ? ? ? continue
? ? ? ? ? ? l = len(tmp_nums)
? ? ? ? ? ? for n1 in range(l - 1):
? ? ? ? ? ? ? ? for n2 in range(n1 + 1,l):
? ? ? ? ? ? ? ? ? ? tmp_cals = cal(tmp_nums[n1],tmp_nums[n2])
? ? ? ? ? ? ? ? ? ? for tmp_cal in tmp_cals:
? ? ? ? ? ? ? ? ? ? ? ? tmp_res = [tmp_cal] + tmp_nums[:n1] + tmp_nums[n1 + 1:n2] + tmp_nums[n2 + 1:]
? ? ? ? ? ? ? ? ? ? ? ? stack.append(tmp_res)
? ? ? ? return False ? ? ? ? ? ? ??
? ? ? ? ? ? ? ??

[Lintcode]739. 24 Game/[Leetcode]679. 24 Game

标签:als   lan   ann   eal   numbers   tput   car   ever   oge   

原文地址:https://www.cnblogs.com/siriusli/p/11191944.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!