473. Matchsticks to Square

https://leetcode.com/problems/matchsticks-to-square/

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

  • code
class Solution {
    private int edgeLen;
    private int n;
    public boolean makesquare(int[] matchsticks) {
        int totalLen = Arrays.stream(matchsticks).sum();
        Arrays.sort(matchsticks);
        edgeLen = totalLen / 4;
        n = matchsticks.length;
        if (4 * edgeLen != totalLen || matchsticks[n-1] > edgeLen) return false;
        return backtrack(n-1, edgeLen, 0, matchsticks);
    }
    private boolean backtrack(int i, int space, int done, int[] nums){
        if (done == 3) return true;
        for (; i >= 0; i--){
            int cur = nums[i];
            boolean res;
            if (cur > space) continue;
            nums[i] = edgeLen + 1;
            if (cur == space) res = backtrack(n-2, edgeLen, done+1, nums);
            else res = backtrack(i-1, space-cur, done, nums);
            if (res) return true;
            nums[i] = cur;
            while (i > 0 && nums[i-1] == cur)
                i--;
        }
        return false;
    }
}