是我自己分的一个类吧,感觉和其他的不太一样
就是把输入的数组中的元素,分成几堆。
目前遇到这几个情况:
(1)这几堆值相同
(2)尽量分均匀,求其中的最大值,即最小的最大值

473. 火柴拼正方形

473. 火柴拼正方形
因为如果有很大的火柴,必然无法拼成正方形,所以排序之后,倒着遍历,能够大大大大提升效率:
image.png

  1. class Solution {
  2. public boolean makesquare(int[] matchsticks) {
  3. int sum=0;
  4. int k=0;
  5. for(int i:matchsticks) sum+=i;
  6. if(sum%4!=0) return false;
  7. else k=sum/4;
  8. int[] path=new int[4];
  9. Arrays.sort(matchsticks);
  10. return backtrack(matchsticks.length-1,k,path,matchsticks);
  11. }
  12. private boolean backtrack(int i,int k,int[] path,int[] matchsticks){
  13. if(i==-1){
  14. return path[0]==path[1]&&path[1]==path[2]&&path[2]==path[3];
  15. }
  16. for(int j=0;j<path.length;j++){
  17. if(path[j]+matchsticks[i]>k) continue;
  18. path[j]+=matchsticks[i];
  19. if(backtrack(i-1, k, path, matchsticks)) return true;
  20. path[j]-=matchsticks[i];
  21. }
  22. return false;
  23. }
  24. }

1723. 完成所有工作的最短时间

1723. 完成所有工作的最短时间
普通方法会超时。
用了一个HashSet来提高效率。

  1. class Solution {
  2. int res=Integer.MAX_VALUE;
  3. public int minimumTimeRequired(int[] jobs, int k) {
  4. int[] worker=new int[k];
  5. backtrack(0,0,worker,jobs);
  6. return res;
  7. }
  8. private void backtrack(int i,int max,int[] worker,int[] jobs){
  9. if(i==jobs.length){
  10. res=Math.min(res,max);
  11. return;
  12. }
  13. Set<Integer> set = new HashSet<>();
  14. for(int j=0;j<worker.length;j++){
  15. //同一层相同的值已经计算过了,就不需要在计算了,直接跳过
  16. if(!set.add(worker[j])) continue;
  17. if(worker[j]+jobs[i]>res) continue;
  18. worker[j]+=jobs[i];
  19. backtrack(i+1, Math.max(max,worker[j]), worker, jobs);
  20. worker[j]-=jobs[i];
  21. }
  22. }
  23. }