LeetCode 473 - Matchsticks to Square - Medium (Python)

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.

Example 1:

Input: [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.

Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You cannot find a way to form a square with all the matchsticks.

卖火柴的小女孩。需要注意的是全部的火柴都要用完。以及不要有一种思维定式,火柴不一定是要连着拿的。比如[5,5,5,5,4,4,4,4,3,3,3,3] 不连续取,是可能形成一个square的。但是如果思维定式火柴连着取,那么得到的结果会是错的。

错误写法
class Solution:
    def makesquare(self, nums: List[int]) -> bool:
        if not nums or len(nums) == 0:
            return False
        if sum(nums) % 4 != 0:
            return False 

        length = sum(nums) // 4
        if any (num > length for num in nums):
            return False
        nums.sort()

        return self.dfs(nums, 0, length, 0, 0)

    def dfs(self, nums, start, length, temp, count):
        if count == 4: return True
        if start > len(nums):
            return True
        if temp == length:
            return self.dfs(nums, start, length, 0, count+1)

        for i in range(start, len(nums)):
            if temp+nums[i] > length:
                break
            if self.dfs(nums, i+1, length, temp+nums[i], count): # wrong!!!
                return True 

正确的思考方式是用dfs遍历可以得到的所有火柴的摆放顺序。如果一味的遍历,那么最后肯定会TLE。一个比较好的方式是构建一个target = [l] * 4. l是可以摆成的火柴的边长。 如果我们可以把这个target的值都变为0,

那么意味着是可以摆成正方形的。

步骤:1 构建target

2 dfs 函数 def dfs(nums, target, pos). dfs跳出条件是 pos == len(nums). 对target进行从0到4的遍历(不包含4),每一次遍历的过程中,对nums也进行一次遍历,如果target[i] >= num, 意味着这个num可能成为

这条边长的candidate,那么我们在这个基础上进行下一层的dfs。注意要把target变为减掉num的target。self.dfs(nums, pos+1, target[:i] + [target[i]-nums[pos]]+target[i+1:])。如果下一层的dfs返回值是True,意味着这些火柴是可以摆放成功的。

比较疑惑的是当nums从大到小排的时候,不会超时。但是从小到大排,就会超。

class Solution:
    def makesquare(self, nums: List[int]) -> bool:
        if not nums or len(nums) == 0:
            return False
        if sum(nums) % 4 != 0:
            return False 

        length = sum(nums) // 4
        if any (num > length for num in nums):
            return False
        nums.sort(reverse = True)
        target = [length] * 4
        return self.dfs(nums, 0,target)

    def dfs(self, nums, pos, target):
        if pos == len(nums):
            return True
        for i in range(4):
            if target[i] >= nums[pos]:
                if self.dfs(nums, pos+1, target[:i] + [target[i]-nums[pos]]+target[i+1:]):
                    return True 

        return False
            

原文地址:https://www.cnblogs.com/sky37/p/12244577.html

时间: 2024-11-13 11:11:10

LeetCode 473 - Matchsticks to Square - Medium (Python)的相关文章

473. Matchsticks to Square

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, a

[LeetCode] 029. Divide Two Integers (Medium) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 029. Divide Two Integers (Medium) 链接: 题目:https://oj.leetcode.com/problems/divide-two-integers/ 代码(github):https://github.com/illuz/leetcode 题意: 实现除法,不能用乘.除和取模

[LeetCode] 035. Search Insert Position (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 035. Search Insert Position (Medium) 链接: 题目:https://leetcode.com/problems/search-insert-position/ 代码(github):https://github.com/illuz/leetcode 题意: 要把一个数有序插入到一

[leetcode] 040. Combination Sum II (Medium) (C++)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql) Github: https://github.com/illuz/leetcode 040. Combination Sum II (Medium) 链接: 题目:https://leetcode.com/problems/combination-sum-ii/ 代码(github):https://github.com/illuz/leetcode 题意: 跟 039 一样(给出一些正整数集合,

leetcode 【 Pascal's Triangle 】python 实现

题目: Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 代码:oj测试通过 Runtime: 46 ms 1 class Solution: 2 # @return a list of lists of integers 3 def generat

[leetcode]Binary Tree Level Order Traversal @ Python

原题地址:http://oj.leetcode.com/problems/binary-tree-level-order-traversal/ 题意:二叉树的层序遍历的实现. 解题思路:二叉树的层序遍历可以用bfs或者dfs来实现.这里使用的dfs实现,代码比较简洁.实际上,二叉树的先序遍历就是dfs实现.   比如一棵树如下: 1 /  \ 2       3 /    \    /   \ 4     5  6    7    二叉树的先序遍历为{1,2,4,5,3,6,7},可以看到这个遍

[leetcode]Search in Rotated Sorted Array @ Python

原题地址:https://oj.leetcode.com/problems/search-in-rotated-sorted-array/ 题意: Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in

[leetcode]Unique Binary Search Trees II @ Python

原题地址:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ 题意:接上一题,这题要求返回的是所有符合条件的二叉查找树,而上一题要求的是符合条件的二叉查找树的棵数,我们上一题提过,求个数一般思路是动态规划,而枚举的话,我们就考虑dfs了.dfs(start, end)函数返回以start,start+1,...,end为根的二叉查找树. 代码: # Definition for a binary tree node #

[leetcode]Copy List with Random Pointer @ Python

原题地址:https://oj.leetcode.com/problems/copy-list-with-random-pointer/ 题意: A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null. Return a deep copy of the list. 解题思路:这题主要是需要深