算法分析与设计第十二周:473. Matchsticks to Square
来源:互联网 发布:java时间戳转换为date 编辑:程序博客网 时间:2024/05/14 07:47
Description:
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
代码:
class Solution(object): def makesquare(self, nums): if len(nums) <= 3: return False res = sum(nums) if res % 4 != 0: return False #sort the array in descending order to decrease the times of searching nums.sort(key = lambda x : -x) cnt = 0 side = res >> 2 if nums[-1] > side: return False def rec(size, length, index , nums, res): if index == size: return res[0] == res[1] and res[1] == res[2] and res[2] == res[3] and res[0] == length for i in range(4): j = i - 1 hasSearched = False #if the length has been searched before, just continue and stop searching for this length while j >= 0: if res[i] == res[j]: hasSearched = True break if hasSearched: continue if res[i] + nums[index]> length: #if the last length can't reach the target length, just return False and stop searching for the remaining matches if i == 3 and res[i] != length: return False continue else: res[i] += nums[index] if rec(size, length, index + 1, nums, res): return True res[i] -= nums[index] return False return rec(len(nums), side, 0, nums, [0, 0, 0, 0])
0 0
- 算法分析与设计第十二周:473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square**
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- LeetCode 473. Matchsticks to Square
- LeetCode 473. Matchsticks to Square
- [leetcode] 473. Matchsticks to Square
- Leetcode-473. Matchsticks to Square
- Leetcode 473. Matchsticks to Square
- [LeetCode]473. Matchsticks to Square
- [leetcode]473. Matchsticks to Square
- 制作自己的数据集 打标签bounding box 之 Windows 10 下python环境安装(PyQt4)
- ATP的CTSC2017现形记
- java基础提高篇--抽象类和接口
- poj 2528 Mayor's posters(树状数组+离散化)
- 求把1,2,3,...,20这20个自然数排成一圈,使任意两个自然数之和为素数
- 算法分析与设计第十二周:473. Matchsticks to Square
- 序列化 Serializable和Parcelable用法及区别
- node.js通过权限验证连接MongoDB
- CVTE 2017春季校招技术类面试问题
- 形参,实参
- Mybatis入门学习一:HelloWorld
- 函数指针和指针函数
- HDU1542 Atlantis 扫描线 矩形面积并
- SpringMVC的WebMvcConfigurerAdapter