diff --git a/src/main/java/leetcode/editor/cn/MatchsticksToSquare.java b/src/main/java/leetcode/editor/cn/MatchsticksToSquare.java
new file mode 100644
index 0000000..7b6e19c
--- /dev/null
+++ b/src/main/java/leetcode/editor/cn/MatchsticksToSquare.java
@@ -0,0 +1,82 @@
+//
你将得到一个整数数组 matchsticks
,其中 matchsticks[i]
是第 i
个火柴棒的长度。你要用 所有的火柴棍 拼成一个正方形。你 不能折断 任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须 使用一次 。
+//
+//如果你能使这个正方形,则返回 true
,否则返回 false
。
+//
+//
+//
+//示例 1:
+//
+//
+//
+//
+//输入: matchsticks = [1,1,2,2,2]
+//输出: true
+//解释: 能拼成一个边长为2的正方形,每边两根火柴。
+//
+//
+//示例 2:
+//
+//
+//输入: matchsticks = [3,3,3,3,4]
+//输出: false
+//解释: 不能用所有火柴拼成一个正方形。
+//
+//
+//
+//
+//提示:
+//
+//
+// 1 <= matchsticks.length <= 15
+// 1 <= matchsticks[i] <= 108
+//
+//Related Topics
位运算数组动态规划回溯状态压缩
👍 316👎 0
+package leetcode.editor.cn;
+
+import java.util.Arrays;
+
+// 473:火柴拼正方形
+public class MatchsticksToSquare {
+ public static void main(String[] args) {
+ Solution solution = new MatchsticksToSquare().new Solution();
+ // TO TEST
+ }
+
+ //leetcode submit region begin(Prohibit modification and deletion)
+ class Solution {
+ public boolean makesquare(int[] matchsticks) {
+ Arrays.sort(matchsticks);
+ int sum = Arrays.stream(matchsticks).sum();
+ if (sum % 4 != 0 || matchsticks[matchsticks.length - 1] > sum / 4) {
+ return false;
+ }
+ int avg = sum / 4;
+ return dfs(matchsticks, matchsticks.length - 1, new int[]{avg, avg, avg, avg});
+ }
+
+ private boolean dfs(int[] matchsticks, int index, int[] sums) {
+ if (index == -1) {
+ for (int i = 0; i < 4; i++) {
+ if (sums[i] != 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ int num = matchsticks[index];
+ for (int i = 0; i < 4; i++) {
+ if (sums[i] - num < 0) {
+ continue;
+ }
+ sums[i] -= num;
+ if (dfs(matchsticks, index - 1, sums)) {
+ return true;
+ }
+ sums[i] += num;
+ }
+ return false;
+ }
+ }
+//leetcode submit region end(Prohibit modification and deletion)
+
+}
diff --git a/src/main/java/leetcode/editor/cn/doc/content/MatchsticksToSquare.md b/src/main/java/leetcode/editor/cn/doc/content/MatchsticksToSquare.md
new file mode 100644
index 0000000..9ef6ea6
--- /dev/null
+++ b/src/main/java/leetcode/editor/cn/doc/content/MatchsticksToSquare.md
@@ -0,0 +1,33 @@
+你将得到一个整数数组 matchsticks
,其中 matchsticks[i]
是第 i
个火柴棒的长度。你要用 所有的火柴棍 拼成一个正方形。你 不能折断 任何一根火柴棒,但你可以把它们连在一起,而且每根火柴棒必须 使用一次 。
+
+如果你能使这个正方形,则返回 true
,否则返回 false
。
+
+
+
+示例 1:
+
+
+
+
+输入: matchsticks = [1,1,2,2,2]
+输出: true
+解释: 能拼成一个边长为2的正方形,每边两根火柴。
+
+
+示例 2:
+
+
+输入: matchsticks = [3,3,3,3,4]
+输出: false
+解释: 不能用所有火柴拼成一个正方形。
+
+
+
+
+提示:
+
+
+ 1 <= matchsticks.length <= 15
+ 1 <= matchsticks[i] <= 108
+
+Related Topics
位运算数组动态规划回溯状态压缩
👍 316👎 0
\ No newline at end of file