473. Matchsticks to Square
Analysis: Similar to 39, 40. But it needs 4 combinations that has equal sum.
Alg1:
Hence one natural approach it to find one target at a time, mark the used number and then recursively find the second one, until the fouth is found.
Alg2:
Second alg is to sort the array in decending order, then find a combination whose sum equals to target, we know that this must be one of the conbination in the answer (no proof yet), hence we can eliminate all other possible first combination and go on to fin the sencond. Same as above, once another combination is found, it must be the “true” second combination, and so on.
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:
1 | Input: [1,1,2,2,2] |
Example 2:
1 | Input: [3,3,3,3,4] |
Note:
- The length sum of the given matchsticks is in the range of
0
to10^9
. - The length of the given matchstick array will not exceed
15
.
Soulution:
1 | # Alg1 |
1 | # Alg2 |