473. Matchsticks to Square

The description of the problem

You are given an integer array of 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.

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/matchsticks-to-square。

An example
在这里插入图片描述

The intuition addressing the above codes

We need to put one of the matchsticks into each edge of the square. After all the matchsticks have been put into the edges, we will return true. Otherwise, we will return false. In these codes, we could use backtracking methods to try out all the possible solutions.

The codes for this problem

#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    bool makesquare(vector<int>& matchsticks) {
		int sum(0);
		sum = accumulate(matchsticks.begin(), matchsticks.end(), 0);
		if (sum % 4) return false;
		sort(matchsticks.begin(), matchsticks.end(), greater<int>());
		int avg = sum / 4;
		vector<int> edges(4, 0);
		return dfs(0, matchsticks, edges, avg);
    }
	bool dfs(int i, vector<int>& matchsticks, vector<int>& edges, int avg) {
		if (i == matchsticks.size()) return true;
		for (int k = 0; k < 4; ++k) {
			edges[k] += matchsticks[i];
			if (edges[k] <= avg && dfs(i + 1, matchsticks, edges, avg)) return true;
			edges[k] -= matchsticks[i];
		}
		return false;
	}
};
int main()
{
	Solution s;
	std::vector<int> matchsticks = {1,10,2,2,2};
	string result = s.makesquare(matchsticks) ? "True" : "False";
	std::cout << "result: " << result << std::endl;
	return 0;
}

The corresponding results

$ ./example
result: False

The basic uses of the accumulate

#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    bool makesquare(vector<int>& matchsticks) {
		int sum(0);
		sum = accumulate(matchsticks.begin(), matchsticks.end(), 0);
		std::cout << "sum: " << sum << std::endl;
		return true;
    }
};
int main()
{
	Solution s;
	std::vector<int> matchsticks = {1,10,2,2,2};
	std::cout << s.makesquare(matchsticks) << std::endl;
	return 0;
}

The above parameters of 0 means the return value type in accumulate function is int.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值