深度优先搜索|473.火柴拼正方形
火柴拼正方形
这个题我本来是想把 i 定为四条边,四条都收到了就结束,但是确实没有办法控制怎么去重复遍历火柴盒,现在的做法是把 i 定为len(matchsticks),然后一次一次的摆到正方形的list里去,一旦发现要超过了就可以摆到下一条边上去,如果摆的下就接着摆。
这里的剪枝是把火柴盒倒序排列了,因为是摆不下了就去下一条边,所以就从大到小往里放比较快一些。
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
if sum(matchsticks) % 4 != 0:
return False
used = [False]*len(matchsticks)
matchsticks.sort(reverse = True) #剪枝
bord = [0]*4
edge = int(sum(matchsticks)/4)
def backtracking(i):
if i == len(matchsticks):
if bord == [edge]*4:
return True
else:
return False
for j in range(4):
if bord[j] + matchsticks[i] > edge: continue
bord[j] += matchsticks[i]
if backtracking(i+1): return True
bord[j] -= matchsticks[i]
return False
return backtracking(0)