473. Matchsticks to Square

473. Matchsticks to Square

Question

You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.

Return true if you can make this square and false otherwise.

Solution

回溯,用int[] edges记录边长。

先计算所有火柴棍的长度之和是否能被4整除,如果不能则返回false。
将所有火柴排序,以减少回溯时的计算量。

Backtracking 回溯

当遍历越界时(传入index为-1),则返回true。

每次将当前火柴matchsticks[index]添加到一个edges[i]中。
当edges[i] <= sum / 4,且向前回溯前一个位置index-1返回结果为真,则返回true。
然后将当前火柴从edges[i]中取出。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
int[] edges;
public boolean makesquare(int[] matchsticks) {
int sum = 0;
for(int i = 0; i < matchsticks.length; i++) sum += matchsticks[i];
if(sum % 4 != 0) return false;

edges = new int[4];
Arrays.sort(matchsticks);
return backtracking(matchsticks, matchsticks.length-1, sum/4);
}

public boolean backtracking(int[] matchsticks, int index, int len){
if(index == -1) return true;

for(int i = 0; i < 4; i++){
edges[i] += matchsticks[index];
if(edges[i] <= len && backtracking(matchsticks, index - 1, len)) return true;
edges[i] -= matchsticks[index];
}
return false;
}
}
Author

Xander

Posted on

2022-07-13

Updated on

2022-07-16

Licensed under

Comments