【回溯】自己想的思路是先分成两份,再看能否把两份继续分
class Solution {
public boolean bk(int[] arr, int sum, int target, int t, int n, int[] ret){
if(t == n){
if(sum == target) return true;
return false;
}else{
ret[t] = 1;
boolean b1 = bk(arr, sum + arr[t], target, t + 1, n, ret);
ret[t] = 0;
boolean b2 = bk(arr, sum, target, t + 1, n, ret);
return b1 || b2;
}
}
boolean ans = false;
public void backTrack(int[] arr, int sum, int target, int t, int n, int[] ret){
if(ans) return;
if(t == n){
if(sum == target){
int t1 = 0, t0 = 0;
for(var i: ret){
if(i == 1) t1++;
else t0++;
}
int[] arr1 = new int[t1];
int[] arr0 = new int[t0];
int j = 0, k = 0, sum1 = 0, sum0 = 0;
for(var i = 0; i < n; i++){
if(ret[i] == 1){
arr1[j++] = arr[i];
sum1 += arr[i];
}
else{
arr0[k++] = arr[i];
sum0 += arr[i];
}
}
int[] ret1 = new int[t1];
int[] ret0 = new int[t0];
if(bk(arr1, 0, sum0 / 2, 0, t1, ret1) && bk(arr0, 0, sum0 / 2, 0, t0, ret0)) ans = true;
}
}else if(sum > target){
return;
}else{
ret[t] = 1;
backTrack(arr, sum + arr[t], target, t + 1, n, ret);
ret[t] = 0;
backTrack(arr, sum, target, t + 1, n, ret);
}
}
public boolean makesquare(int[] matchsticks) {
int[] ma = matchsticks;
int sum = 0;
for(var i: ma) sum += i;
if(sum % 4 != 0) return false;
int n = ma.length;
int[] bin = new int[n];
backTrack(ma, 0, sum / 2, 0, n, bin);
return ans;
}
}
【方法二】可以借鉴698. 划分为k个相等的子集 的方法,这里的k固定为4了。
class Solution {
// 7:44 9min
public boolean backTrack(int[] ma, int t, int n, int[] bucket){
if(t == n) return true;
for(var i = 0; i < 4; i++){
if(i != 0 && bucket[i] == bucket[i - 1]) continue;
if(ma[t] <= bucket[i]){
bucket[i] -= ma[t];
if(backTrack(ma, t + 1, n, bucket)) return true;
bucket[i] += ma[t];
}
}
return false;
}
public boolean makesquare(int[] matchsticks) {
int sum = 0;
for(var i: matchsticks) sum += i;
if(sum % 4 != 0) return false;
int[] ma = Arrays.stream(matchsticks).boxed().sorted((a, b) -> b - a).mapToInt(t -> t).toArray();
int n = ma.length, m = sum / 4;
int[] bucket = new int[4];
Arrays.fill(bucket, m);
return backTrack(ma, 0, n, bucket);
}
}