Welcome to Subscribe On Youtube

473. Matchsticks to Square

Description

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

Solutions

Solution 1: Depth-First Search + Sorting

Use $edges[i]$ to record the current length of each side of the square. For the $u$ match, try to add it to each side of $edges[i]$. If $edges[i]$ does not exceed the expected length of the square $x$ after adding it, continue to recurse down to $u+1$ matches. If all the matches can be added, it means that the requirements for forming a square are met.

Here, $matchsticks$ is sorted from large to small to reduce the number of searches.

Time complexity $O(4^n)$, where $n$ represents the length of $matchsticks$. Each match can be placed into the $4$ edges of the square, for a total of $n$ matches.

Solution 2

Remember the current division of matches as $state$. For the $i$th number, if $state \ \& \ (1«i)=0$, it means that the $i$th matchstick has not been divided. Our goal is to find $k$ subsets that sum to $s$ from all the numbers.

Note that the sum of the current subsets is $t$. When matchstick $i$ is not divided:

  • If $t+matchsticks[i]>s$, it means that the $i$th matchstick cannot be added to the current subset. Since we arrange the $matchsticks$ array in ascending order, all numbers starting from $matchsticks$ and the $i$th matchstick cannot be added to the current subset, and $false$ is returned directly.
  • Otherwise, add the $i$th matchstick to the current subset, change the status to $state \ \ (1«i)$, and continue searching for undivided numbers.

Note: If $t+matchsticks[i]==s$, it means that a subset whose sum is $s$ can be obtained. The next step is to reset $t$ to zero (which can be achieved by $(t+matchsticks[i]) \%s$), and continue to divide the next subset.

  • class Solution {
        public boolean makesquare(int[] matchsticks) {
            int s = 0, mx = 0;
            for (int v : matchsticks) {
                s += v;
                mx = Math.max(mx, v);
            }
            int x = s / 4, mod = s % 4;
            if (mod != 0 || x < mx) {
                return false;
            }
            Arrays.sort(matchsticks);
            int[] edges = new int[4];
            return dfs(matchsticks.length - 1, x, matchsticks, edges);
        }
    
        private boolean dfs(int u, int x, int[] matchsticks, int[] edges) {
            if (u < 0) {
                return true;
            }
            for (int i = 0; i < 4; ++i) {
                if (i > 0 && edges[i - 1] == edges[i]) {
                    continue;
                }
                edges[i] += matchsticks[u];
                if (edges[i] <= x && dfs(u - 1, x, matchsticks, edges)) {
                    return true;
                }
                edges[i] -= matchsticks[u];
            }
            return false;
        }
    }
    
    
  • class Solution {
    public:
        bool makesquare(vector<int>& matchsticks) {
            int s = 0, mx = 0;
            for (int& v : matchsticks) {
                s += v;
                mx = max(mx, v);
            }
            int x = s / 4, mod = s % 4;
            if (mod != 0 || x < mx) return false;
            sort(matchsticks.begin(), matchsticks.end(), greater<int>());
            vector<int> edges(4);
            return dfs(0, x, matchsticks, edges);
        }
    
        bool dfs(int u, int x, vector<int>& matchsticks, vector<int>& edges) {
            if (u == matchsticks.size()) return true;
            for (int i = 0; i < 4; ++i) {
                if (i > 0 && edges[i - 1] == edges[i]) continue;
                edges[i] += matchsticks[u];
                if (edges[i] <= x && dfs(u + 1, x, matchsticks, edges)) return true;
                edges[i] -= matchsticks[u];
            }
            return false;
        }
    };
    
    
  • class Solution:
        def makesquare(self, matchsticks: List[int]) -> bool:
            def dfs(u):
                if u == len(matchsticks):
                    return True
                for i in range(4):
                    if i > 0 and edges[i - 1] == edges[i]:
                        continue
                    edges[i] += matchsticks[u]
                    if edges[i] <= x and dfs(u + 1):
                        return True
                    edges[i] -= matchsticks[u]
                return False
    
            x, mod = divmod(sum(matchsticks), 4)
            if mod or x < max(matchsticks):
                return False
            edges = [0] * 4
            matchsticks.sort(reverse=True)
            return dfs(0)
    
    
    # Solution 2
    class Solution:
        def makesquare(self, matchsticks: List[int]) -> bool:
            @cache
            def dfs(state, t):
                if state == (1 << len(matchsticks)) - 1:
                    return True
                for i, v in enumerate(matchsticks):
                    if state & (1 << i):
                        continue
                    if t + v > s:
                        break
                    if dfs(state | (1 << i), (t + v) % s):
                        return True
                return False
    
            s, mod = divmod(sum(matchsticks), 4)
            matchsticks.sort()
            if mod:
                return False
            return dfs(0, 0)
    
    
  • func makesquare(matchsticks []int) bool {
    	s := 0
    	for _, v := range matchsticks {
    		s += v
    	}
    	if s%4 != 0 {
    		return false
    	}
    	sort.Sort(sort.Reverse(sort.IntSlice(matchsticks)))
    	edges := make([]int, 4)
    	var dfs func(u, x int) bool
    	dfs = func(u, x int) bool {
    		if u == len(matchsticks) {
    			return true
    		}
    		for i := 0; i < 4; i++ {
    			if i > 0 && edges[i-1] == edges[i] {
    				continue
    			}
    			edges[i] += matchsticks[u]
    			if edges[i] <= x && dfs(u+1, x) {
    				return true
    			}
    			edges[i] -= matchsticks[u]
    		}
    		return false
    	}
    	return dfs(0, s/4)
    }
    
  • impl Solution {
        pub fn makesquare(matchsticks: Vec<i32>) -> bool {
            let mut matchsticks = matchsticks;
    
            fn dfs(matchsticks: &Vec<i32>, edges: &mut [i32; 4], u: usize, x: i32) -> bool {
                if u == matchsticks.len() {
                    return true;
                }
                for i in 0..4 {
                    if i > 0 && edges[i - 1] == edges[i] {
                        continue;
                    }
                    edges[i] += matchsticks[u];
                    if edges[i] <= x && dfs(matchsticks, edges, u + 1, x) {
                        return true;
                    }
                    edges[i] -= matchsticks[u];
                }
                false
            }
    
            let sum: i32 = matchsticks.iter().sum();
            if sum % 4 != 0 {
                return false;
            }
            matchsticks.sort_by(|x, y| y.cmp(x));
            let mut edges = [0; 4];
    
            dfs(&matchsticks, &mut edges, 0, sum / 4)
        }
    }
    
    

All Problems

All Solutions