leetcode match spell square deep search

Remember the fairy tale "The Little Match Girl" it? Now that you know how many little girls have a match, please find a match can be used for all makes up a square method. Can not break matches, the matches can be connected, and each match should be used.

Girl has input the number of matches, each match indicated by the length thereof. Output that is if you can use all the matches spell square.

Example 1:

Input: [1,1,2,2,2]
Output: true

Explanation: energy makes up a square side length of 2, two on each side matches.
Example 2:

Input: [3,3,3,3,4]
Output: false

Explanation: You can not spell a square with all the matches.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/matchsticks-to-square

Ideas: 1. Human predetermined length matches the length of each side starts to fill (to avoid more cases
each side length of the order of enumeration large 2.
3. Pruning: after a match fails length, with the same length matches will not work, skip these circumstances; if the current composition of the side length of the match is the first or last, but after the failure, so this situation is not great, you must cut off all

class Solution {
public:
    vector<bool> st;
    bool makesquare(vector<int>& nums) {
        int sum=0;
        st=vector<bool>(nums.size());
        sort(nums.begin(),nums.end());
        reverse(nums.begin(),nums.end());
        for(auto t:nums)sum+=t;
        if(sum%4||!nums.size())return false;
        return dfs(0,0,sum/4,nums,0);
    }
    bool dfs(int cur,int len,int max_len,vector<int>& nums,int start){
        if(cur==4)return true;
        if(len==max_len)return dfs(cur+1,0,max_len,nums,0);
        for(int i=start;i<nums.size();++i){
            if(!st[i]&&len+nums[i]<=max_len){
                st[i]=true;
                if(dfs(cur,len+nums[i],max_len,nums,i+1))return true;
                st[i]=false;
                if(!len)return false;
                if(len+nums[i]==max_len)return false;
                while(i+1<nums.size()&&nums[i+1]==nums[i])i++;
            }
        }
        return false;
    }
};

Guess you like

Origin www.cnblogs.com/clear-love/p/11370029.html