leetcode473 火柴拼正方形

回溯法

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

class Main {
    public boolean makesquare(int[] matchsticks) {
        int totalLen = Arrays.stream(matchsticks).sum();
        if (totalLen % 4 != 0) {
            return false;
        }
        Arrays.sort(matchsticks);
        for (int i = 0, j = matchsticks.length - 1; i < j; i++, j--) {
            int temp = matchsticks[i];
            matchsticks[i] = matchsticks[j];
            matchsticks[j] = temp;
        }

        int[] edges = new int[4];
        return dfs(0, matchsticks, edges, totalLen / 4);
    }

    public boolean dfs(int index, int[] matchsticks, int[] edges, int len) {
        if (index == matchsticks.length) {
            return true;
        }
        for (int i = 0; i < edges.length; i++) {
            edges[i] += matchsticks[index];
            if (edges[i] <= len && dfs(index + 1, matchsticks, edges, len)) {
                return true;
            }
            edges[i] -= matchsticks[index];
        }
        return false;
    }

    public static void main(String[] args) {
        int[] nums = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,102};
        Main main = new Main();
        System.out.println(main.makesquare(nums));
    }
}


相关推荐

  1. leetcode473 火柴正方形

    2024-03-29 17:00:02       16 阅读
  2. 有效的正方形LeetCode 593)

    2024-03-29 17:00:02       24 阅读
  3. [leetcode 差分数组] 车 M

    2024-03-29 17:00:02       35 阅读
  4. leetcode 437 路径总和

    2024-03-29 17:00:02       37 阅读
  5. LeetCode //C - 443. String Compression

    2024-03-29 17:00:02       42 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-03-29 17:00:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-03-29 17:00:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-03-29 17:00:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-03-29 17:00:02       20 阅读

热门阅读

  1. vue前端播放视频

    2024-03-29 17:00:02       19 阅读
  2. React组件及组件通讯

    2024-03-29 17:00:02       17 阅读
  3. 企业文化与就业年龄歧视问题

    2024-03-29 17:00:02       18 阅读
  4. AQS

    2024-03-29 17:00:02       16 阅读
  5. Python从零到一构建GPT模型

    2024-03-29 17:00:02       19 阅读
  6. git之目前的主流版本

    2024-03-29 17:00:02       26 阅读
  7. day 41 动归 04

    2024-03-29 17:00:02       18 阅读
  8. RocketMq总结

    2024-03-29 17:00:02       16 阅读