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.