# Leetcode 473：火柴拼正方形（超详细的解法！！！）

输入: [1,1,2,2,2]



输入: [3,3,3,3,4]



• 给定的火柴长度和在010^9之间。
• 火柴数组的长度不超过15

class Solution:
def makesquare(self, nums: List[int]) -> bool:
s, n = sum(nums), len(nums)
t = s//4
if len(nums) < 4 or s % 4:
return False

data = [0] * 4

def dfs(u):
if u == n:
if all(i == t for i in data):
return True
return False

for i in range(4):
if data[i] + nums[u] > t: continue

data[i] += nums[u]
if dfs(u + 1): return True
data[i] -= nums[u]
return False

return dfs(0)


class Solution:
def makesquare(self, nums: List[int]) -> bool:
s, n = sum(nums), len(nums)
t = s//4
if len(nums) < 4 or s % 4:
return False

vis = [0] * n

def dfs(cur, u, k):
"""
cur: 当前边（第u条边）的长度
u: 第几条边
k: nums中的第k个数
"""
if u == 4: return True
if cur == t: return dfs(0, u + 1, 0) # 摆下一个边

i = k
while i < n:
if vis[i] or (cur + nums[i] > t):
i += 1
continue

vis[i] = 1
if dfs(cur + nums[i], u, i + 1): return True
vis[i] = 0
i += 1

return False

return dfs(0, 0, 0)


class Solution:
def makesquare(self, nums: List[int]) -> bool:
s, n = sum(nums), len(nums)
t = s//4
if len(nums) < 4 or s % 4:
return False

nums.sort(reverse=True)
vis = [0] * n

def dfs(cur, u, k):
if u == 4: return True
if cur == t: return dfs(0, u + 1, 0)

i = k
while i < n:
if vis[i] or (cur + nums[i] > t):
i += 1
continue

vis[i] = 1
if dfs(cur + nums[i], u, i + 1): return True
vis[i] = 0

# 针对每条边的第一个和最后一个火柴
if not cur or cur + nums[i] == t: return False

j = i
while j < n and nums[i] == nums[j]: j += 1 # 相同火柴
i = j - 1
i += 1
return False

return dfs(0, 0, 0)


©️2019 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客