엔지니어 게시판
LeetCode 솔루션 분류

[7/12] 473. Matchsticks to Square

컨텐츠 정보

본문

Medium
1782140Add to ListShare

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 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)
    
    
전체 410 / 1 페이지
번호
제목
이름

최근글


인기글


새댓글


Stats


알림 0