zoukankan      html  css  js  c++  java
  • Leetcode: 473. Matchsticks to Square

    Description

    You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
    
    Return true if you can make this square and false otherwise.
    

    Example

    Input: matchsticks = [1,1,2,2,2]
    Output: true
    Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
    

    Code

    class Solution(object):
        def makesquare(self, arr):
            """
            :type matchsticks: List[int]
            :rtype: bool
            """
            rec_len = sum(arr) // 4
            if sum(arr) % 4 > 0:
                return False 
            h = {0:0}
            candidate = []
            seen = set()
           
            if any([v > rec_len for v in arr]):
                return False
            
            bits = sum([(1 << i) for i in range(len(arr))])
            
            for i in range(len(arr)):    # 先把满足边的组合计算出来,用于后续迭代。耗时 369 ms, 战胜了 93 % 的提交。不用这个方法会 TLE 的
                                               # 采用 dfs 的话,代码很容易实现。但是耗时会变成 1500 ms + 
                tmp = {}
                for k in h:
                    if rec_len > h[k] + arr[i]:
                        tmp[k | (1 << i)] = h[k] + arr[i]
                    elif rec_len == h[k] + arr[i]:
                        candidate.append(k | (1 << i))
                h.update(tmp) 
                
            h = {0:0}
            for v in candidate:
                tmp = {}
                for s in h:
                    if s & v == 0:
                        if s | v == bits:
                            return True
                        tmp[s | v] = 0
                h.update(tmp)
            return False
    
  • 相关阅读:
    微服务负载均衡技术
    dubbo 协议注册中心
    dubbo 元数据中心
    @Autowired 写在构造方法上
    onchange事件 is not defined
    转:JNDI的本质及作用
    The valid characters are defined in RFC 7230 and RFC 3986报错处理
    FOR XML PATH 简单介绍
    ROW_NUMBER() OVER函数的基本用法
    java和js中JSONObject,JSONArray,Map,String之间转换
  • 原文地址:https://www.cnblogs.com/tmortred/p/15675284.html
Copyright © 2011-2022 走看看