链接:473. 火柴拼正方形
题解:
class Solution {
private:
bool dfs(int begin, std::vector<int> edges, int len, const vector<int>& matchsticks) {
// 所有的火柴均已经使用
if (begin >= matchsticks.size()) {
return true;
}
// 填充4个边
for (int i = 0; i < edges.size(); ++i) {
edges[i] += matchsticks[begin];
// 如果边已经填充好了
if (edges[i] <= len) {
// 成功
if (dfs(begin+1, edges, len, matchsticks)) {
return true;
}
}
edges[i] -= matchsticks[begin];
}
return false;
}
public:
bool makesquare(vector<int>& matchsticks) {
int total_len = accumulate(matchsticks.begin(), matchsticks.end(), 0);
// 总长度不能构成4条边
if (total_len % 4 != 0) {
return false;
}
sort(matchsticks.begin(), matchsticks.end(), greater<int>());
int begin = 0;
// 初始化4条边为0
std::vector<int> edges(4, 0);
return dfs(begin, edges, total_len/4, matchsticks);
}
};