Leetcode 473. Matchsticks to Square 卖火柴的小女孩画框框 解题报告
来源:互联网 发布:c语言中10的n次方 编辑:程序博客网 时间:2024/05/17 08:58
1 解题思想
这道题的意思就是卖火柴的小女孩有一堆长度不等的火柴,他希望拼成一个正方形,不知道可以不可以?
所谓可以就是:
1、用了所有火柴,一根不多,一根不少,当然一根用一次
2、四条边长度一样
所以这道题做法,我用了DFS,就是不停的搜索就好。。。控制好边界时间就好。。。我也不知道有什么很特别的做法
2 原题
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 can save this little girl or not.Example 1:Input: [1,1,2,2,2]Output: trueExplanation: 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: falseExplanation: 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 0 to 10^9.The length of the given matchstick array will not exceed 15.
3 AC解
public class Solution { public boolean makesquare(int[] nums) { if (nums == null || nums.length < 4) return false; int sum = 0; for (int num : nums) sum += num; if (sum % 4 != 0) return false; return dfs(nums, new int[4], 0, sum/4); } private boolean dfs(int[] nums, int[] sums, int index, int target) { if (index == nums.length){ if(sums[0] == target && sums[1] == target && sums[2] == target ) return true; return true; } for(int i=0;i<4;i++){ if(sums[i] + nums[index] <= target){ sums[i] += nums[index]; if(dfs(nums,sums,index+1,target)) return true; sums[i] -= nums[index]; } } return false; }}
0 0
- Leetcode 473. Matchsticks to Square 卖火柴的小女孩画框框 解题报告
- [Leetcode] 473. Matchsticks to Square 解题报告
- LeetCode 473. Matchsticks to Square
- LeetCode 473. Matchsticks to Square
- [leetcode] 473. Matchsticks to Square
- Leetcode-473. Matchsticks to Square
- Leetcode 473. Matchsticks to Square
- [LeetCode]473. Matchsticks to Square
- [leetcode]473. Matchsticks to Square
- LeetCode: Matchsticks to Square
- LeetCode: Matchsticks to Square
- [LeetCode] Matchsticks to Square
- Leetcode: Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square**
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 473. Matchsticks to Square
- 求hack or 证明(【JZOJ 4923】 【NOIP2017提高组模拟12.17】巧克力狂欢)
- java 基础
- linux上安装运行Jmeter
- filestream 用法
- 关闭toast权限后自定义解决方式
- Leetcode 473. Matchsticks to Square 卖火柴的小女孩画框框 解题报告
- 丰富多彩的2016—未来属于我
- python关于用BeautifulSoup爬取网易动态评论
- iOS画虚线方法
- Qt学习笔记3:Qt工程的目录结构
- Spring Batch 构建批处理应用2
- 内部类详解
- angularJS1 ng-include相同html部分重用
- leetcode 60 第几个排列