473 Matchsticks to Square | 打满鸡血来刷题
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:
|
|
Example 2:
|
|
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
.
思路
利用深度优先搜索可以解决这道题。
正方形的四边长都是一样的。如果数组里的所有元素之和不能被4整除,则不能被拼成一个正方形。如果可以被四整除,我们可以一步步往下搜索,直到找到一个可行的拼法。
我们在做DFS的时候,需要一条边一条边进行搜索。edge_size是待寻找的边的长度,找到一条边,edge_count-1。cur_edge是当前找到的所有边长度的总和。
Read full article from 473 Matchsticks to Square | 打满鸡血来刷题
No comments:
Post a Comment