Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.
Example 1:
Input: [1,1,2,2,2] Output: true Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: [3,3,3,3,4] Output: false Explanation: You cannot find a way to form a square with all the matchsticks.
Note:
- The length sum of the given matchsticks is in the range of
0to10^9. - The length of the given matchstick array will not exceed
15.
class Solution {
bool chkSquare(const vector<int>& nums, vector<int>& len, int idx, int sdLen) {
if(idx == nums.size()) {
if(len[0] == sdLen && len[1] == sdLen && len[2] == sdLen)
return true;
else return false;
}
for(int i=0; i<4; ++i) {
if(len[i] + nums[idx] <= sdLen) {
len[i] += nums[idx];
if(chkSquare(nums, len, idx+1, sdLen)) return true;
len[i] -= nums[idx];
}
}
return false;
}
public:
bool makesquare(vector<int>& nums) {
if(nums.size() < 4) return false;
vector<int> len(4, 0);
int total = accumulate(nums.begin(), nums.end(), 0);
if(total%4) return false;
sort(nums.begin(), nums.end(), greater<int>());
return chkSquare(nums, len, 0, total/4);
}
};
探讨如何利用小火柴女孩所有的火柴棒不折断的情况下拼成一个正方形的问题,通过算法验证是否可行。
172

被折叠的 条评论
为什么被折叠?



