首页 > 其他 > 详细

火柴拼正方形

时间:2021-08-04 22:35:14      阅读:29      评论:0      收藏:0      [点我收藏+]

题目链接: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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!