Leetcode之深度优先搜索(DFS)专题-473. 火柴拼正方形(Matchsticks to Square)

时间:2023-03-09 06:53:00
Leetcode之深度优先搜索(DFS)专题-473. 火柴拼正方形(Matchsticks to Square)

Leetcode之深度优先搜索(DFS)专题-473. 火柴拼正方形(Matchsticks to Square)

深度优先搜索的解题详细介绍,点击


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

输入为小女孩拥有火柴的数目,每根火柴用其长度表示。输出即为是否能用所有的火柴拼成正方形。

示例 1:

输入: [1,1,2,2,2]
输出: true 解释: 能拼成一个边长为2的正方形,每边两根火柴。
示例 2: 输入: [3,3,3,3,4]
输出: false 解释: 不能用所有火柴拼成一个正方形。
注意: 给定的火柴长度和在 0 到 10^9之间。
火柴数组的长度不超过15。

分析:

拼火柴,那我们首先有几个特判:

1、数组元素和不是4的倍数的,不能拼成正方形

2、数组元素中有比sum/4大的,不能

然后就写DFS函数,参数可以定为四个边,当4个边的值都等于sum/4时,即可。

同时注意剪枝,即当四条边中任意一条大于sum/4时,返回。

AC代码:

class Solution {
public boolean makesquare(int[] nums) {
if(nums.length==0) return false;
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
if (sum % 4 != 0)
return false;
int target = (sum / 4);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > target) {
return false;
}
}
Arrays.sort(nums);
return dfs(nums, nums.length - 1, 0, 0, 0, 0,target);
} public boolean dfs(int[] nums, int step, int a1, int a2, int a3,
int a4,int target) {
if (step < 0) {
if (a1 == target && a2 == target && a3 ==target && a4==target) {
return true;
}
return false;
}
if(a1>target || a2>target || a3>target || a4>target){
return false;
}
return dfs(nums, step - 1, a1 + nums[step], a2, a3, a4,target)
|| dfs(nums, step - 1, a1, a2 + nums[step], a3, a4,target)
|| dfs(nums, step - 1, a1, a2, a3 + nums[step], a4,target)
|| dfs(nums, step - 1, a1, a2, a3, a4 + nums[step],target);
} }