473. 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
  • 0 <= matchsticks[i] <= 109
class Solution {
    public boolean makesquare(int[] nums) {
        int k = 4;
        if(nums.length < k) return false;
        int sum = 0;
        for(int i : nums) sum += i;
        if(sum % k != 0) return false;
        boolean[] visited = new boolean[nums.length];
        return dfs(visited, nums, 0, 0, sum / k, k);
    }
    
    public boolean dfs(boolean[] visited, int[] nums, int start, int cur, int target, int k) {
        if(k == 0) return true;
        
        if(cur == target) return dfs(visited, nums, 0, 0, target, k - 1);
        for(int i = start; i < nums.length; i++) {
            if(visited[i] || cur + nums[i] > target) continue;
            visited[i] = true;
            if(dfs(visited, nums, i + 1, cur + nums[i], target, k)) return true;
            visited[i] = false;
        }
        return false;
    }
}

问的是能不能用给定的火柴数组搭出来一个正方形,换句话说,就是能不能把火柴平分成4份,用dfs来做。

cur是当前的sum,有两个地方能进入dfs,一个是cur==target的时候说明第一组火柴弄好了,进行到下一组。visited是防止重复的数组。

另一个是计算当前的cur时,尝试所有可能,记得剪枝。

本题和698一模一样。

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14887986.html