[473]Matchsticks to Square

leetcode

My Solution

This question is talking about split the array into 4 groups, they equal to each other.

-- sum the array and divide by 4, calculate the length of edge.
-- using dfs solution, to divide each number into 4 group, to check true or false.
-- when divide, check whether each group sum larger than edge.

public class Solution {
    public boolean makesquare(int[] nums) {
        
        int sum = 0;
        for (int num : nums) {
            sum += num;
        }

        if (sum % 4 != 0 || sum == 0) return false;

        int edge = sum / 4;
        int[] box = new int[4];

        if(helper(nums,box,edge,0)){
            for(int b : box){
                if(b != edge)return false;
            }
            return true;
        }

        return false;

    }

    public boolean helper(int[] nums, int[] box, int edge, int start) {
        if (start == nums.length) return true;

        int n = nums[start];

        for (int i = 0; i < 4; i++) {
            if (box[i] + n <= edge) {
                box[i] += n;
                if (helper(nums, box, edge, start + 1)) return true;
                box[i] -= n;
            }
        }
        return false;
    }


}

optimization

Sort the array in descending order can speed up the dfs.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 今早八点半阅读完 刚从有爸爸、有妈妈的家里回到南宁的住所,本来想追剧来着,想想任务没完成,我只能把我亲爱的大幂幂延...
    书叶随风阅读 428评论 0 0
  • 听说你要来, 我盛装打扮。 等在你必经的路旁, 只为一睹你容颜。 从清晨到日暮, 从日暮到清晨。 为伊消瘦了容颜,...
    a雪落阅读 265评论 0 1
  • 朋友,不是亲人,也不是路人,更不是仇人。 朋友来源很多,类型大致几种:校友、酒肉朋友、事业上的朋友、感情上的朋友、...
    执笔绘七星阅读 152评论 0 0
  • 坚持一件事是不容易的,这两天深有体会,平时我们借口太多,想做的事总是往后推,比如,今天很晚了,明天做吧,今...
    蝉翼呵呵阅读 277评论 0 1