Leetcode brushing question: match matches to make a square

topic:
insert image description here

Analysis:
The basic idea is to search whether there is a subsequence with the sum of sum/4 in the array, and search four times in total. Each time, the used marks should be considered
[1,1,2,2,3,3,4], If [1,1,2] is combined first, then the latter cannot be combined into 4. In this case, we should search from large to small, because small values ​​can always be pieced together. So you need to sort the array in reverse order first. Then search from front to back.

code show as below:

class Solution {
public:
    bool makesquare(vector<int>& nums) 
    {
        int n = nums.size();
        if (n < 4) return false;
        sort(nums.begin(), nums.end(), greater<int>()); //逆排
        int sum = accumulate(nums.begin(), nums.end(), 0); //累加和
        if (sum % 4 != 0) return false;  
        sum /= 4;
        vector<bool> vis(n, false);  //记录是否被用过
        for (int i = 0; i < 4; i++)  //四条边都搜索
        {
            if (!dfs(nums, vis, 0, sum)) return false;
        }
        return true;
    }

    bool dfs(vector<int> &nums, vector<bool> &vis, int k, int sum){
        int n = nums.size();
        if(sum==0) return true;
        for(int i=k; i<n; ++i){
            if(nums[i]<=sum && !vis[i]){
                vis[i] = true;
                if(dfs(nums, vis, i+1, sum-nums[i])) return true;  //组合成功就返回,不需要继续搜索。
                vis[i] = false;  //如果组合失败,需要释放该数
            }
        }
        return false;
    }

};

Guess you like

Origin blog.csdn.net/weixin_43907175/article/details/122902262