leetcode 473. Matchsticks to Square | 473. 火柴拼正方形(递归)

太过爱你忘了你带给我的痛 2022-09-09 09:55 246阅读 0赞

题目

https://leetcode.com/problems/matchsticks-to-square/
在这里插入图片描述

题解

看了 hint 之后,才有思路。
在这里插入图片描述

讨论区有个人说得好:

This solution should mention that this problem is an instance of the well-known Bin Packing Problem, which has been proven to be NP-complete, so it is not possible to implement a solution that takes less than exponential time. This would be a very important fact for the candidate to identify, because they otherwise will likely spin their wheels trying to identify a polynomial-time solution.

Once you’ve identified that the problem is NP-complete, you know that you’ll just have to implement a “brute force” solution, and the only task remaining is to look for opportunities to reduce the amount of work you need to do via pruning, memoization, etc.

Exactly. In fact second solution is over-engineering because there isn’t an actual improvement in big o time complexity.

If I was the interviewer, if the candidate identified that it’s a variant of bin-packing, therefore NP-complete, and gave a clean backtracking solution, that would be full marks.

  1. class Solution {
  2. public boolean makesquare(int[] arr) {
  3. Arrays.sort(arr);
  4. int sum = 0;
  5. for (int m : arr) {
  6. sum += m;
  7. }
  8. if (sum % 4 != 0) return false;
  9. return process(arr, arr.length - 1, 0, 0, 0, 0, sum / 4);
  10. }
  11. public boolean process(int[] arr, int i, int l1, int l2, int l3, int l4, int target) {
  12. if (i < 0) return l1 == target && l2 == target && l3 == target && l4 == target;
  13. if (l1 > target || l2 > target || l3 > target || l4 > target) return false;
  14. return process(arr, i - 1, l1 + arr[i], l2, l3, l4, target) ||
  15. process(arr, i - 1, l1, l2 + arr[i], l3, l4, target) ||
  16. process(arr, i - 1, l1, l2, l3 + arr[i], l4, target) ||
  17. process(arr, i - 1, l1, l2, l3, l4 + arr[i], target);
  18. }
  19. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,246人围观)

还没有评论,来说两句吧...

相关阅读

    相关 leetcode 火柴正方形 深搜

    > 还记得童话《卖火柴的小女孩》吗?现在,你知道小女孩有多少根火柴,请找出一种能使用所有火柴拼成一个正方形的方法。不能折断火柴,可以把火柴连接起来,并且每根火柴都要用到。 >