是我自己分的一个类吧,感觉和其他的不太一样
就是把输入的数组中的元素,分成几堆。
目前遇到这几个情况:
(1)这几堆值相同
(2)尽量分均匀,求其中的最大值,即最小的最大值
473. 火柴拼正方形
473. 火柴拼正方形
因为如果有很大的火柴,必然无法拼成正方形,所以排序之后,倒着遍历,能够大大大大提升效率:
class Solution {
public boolean makesquare(int[] matchsticks) {
int sum=0;
int k=0;
for(int i:matchsticks) sum+=i;
if(sum%4!=0) return false;
else k=sum/4;
int[] path=new int[4];
Arrays.sort(matchsticks);
return backtrack(matchsticks.length-1,k,path,matchsticks);
}
private boolean backtrack(int i,int k,int[] path,int[] matchsticks){
if(i==-1){
return path[0]==path[1]&&path[1]==path[2]&&path[2]==path[3];
}
for(int j=0;j<path.length;j++){
if(path[j]+matchsticks[i]>k) continue;
path[j]+=matchsticks[i];
if(backtrack(i-1, k, path, matchsticks)) return true;
path[j]-=matchsticks[i];
}
return false;
}
}
1723. 完成所有工作的最短时间
1723. 完成所有工作的最短时间
普通方法会超时。
用了一个HashSet来提高效率。
class Solution {
int res=Integer.MAX_VALUE;
public int minimumTimeRequired(int[] jobs, int k) {
int[] worker=new int[k];
backtrack(0,0,worker,jobs);
return res;
}
private void backtrack(int i,int max,int[] worker,int[] jobs){
if(i==jobs.length){
res=Math.min(res,max);
return;
}
Set<Integer> set = new HashSet<>();
for(int j=0;j<worker.length;j++){
//同一层相同的值已经计算过了,就不需要在计算了,直接跳过
if(!set.add(worker[j])) continue;
if(worker[j]+jobs[i]>res) continue;
worker[j]+=jobs[i];
backtrack(i+1, Math.max(max,worker[j]), worker, jobs);
worker[j]-=jobs[i];
}
}
}