火柴拼正方形

时间:2021-08-04
本文章向大家介绍火柴拼正方形,主要包括火柴拼正方形使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题目链接:https://leetcode-cn.com/problems/matchsticks-to-square/
题目描述:

题解:

class Solution {
public:
    bool makesquare(vector<int>& matchsticks) {
        vector<bool> used(matchsticks.size(), false);
        int sum = 0;
        for(auto &item : matchsticks)
        {
            sum += item;
        }
        if(sum % 4 != 0)
            return false;
        int target = sum / 4;
        sort(matchsticks.begin(), matchsticks.end());
        return trackingBack(matchsticks, 0, 0, target, 4, used);
   
    }
    bool trackingBack(vector<int>& matchsticks,int index, int pathSum, int target, int k, vector<bool>& used)
     {
        if(k == 0)
            return true;
        if(pathSum == target)
            return trackingBack(matchsticks, 0, 0, target, k - 1, used);
        for(int i = index; i < matchsticks.size() && matchsticks[i] + pathSum <= target; i++)
        {
            if(used[i] == true)
                continue;
            if(i > 0 && matchsticks[i] == matchsticks[i - 1] && used[i - 1] == false)
                continue;
            pathSum += matchsticks[i];
            used[i] = true;
            if(trackingBack(matchsticks, i + 1, pathSum, target, k, used))
                return true;
            pathSum -= matchsticks[i];
            used[i] = false;
        }
        return false;      
    } 
};

原文地址:https://www.cnblogs.com/ZigHello/p/15100860.html