LeetCode 솔루션 분류
[7/12] 473. Matchsticks to Square
본문
Medium
1782140Add to ListShareYou 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 1:
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.
Example 2:
Input: matchsticks = [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Constraints:
1 <= matchsticks.length <= 15
1 <= matchsticks[i] <= 108
관련자료
-
링크
댓글 1
학부유학생님의 댓글
- 익명
- 작성일
class Solution:
def makesquare(self, matchsticks: List[int]) -> bool:
total_sum = sum(matchsticks)
if total_sum%4: return False
matchsticks.sort(reverse=True)
targets = [total_sum//4]*4
def dfs(match_idx):
if match_idx == len(matchsticks): return True
for i in range(4):
if targets[i]>=matchsticks[match_idx]:
targets[i] -= matchsticks[match_idx]
if dfs(match_idx+1): return True
targets[i]+=matchsticks[match_idx]
return False
return dfs(0)