473. Matchsticks to Square

https://www.acwing.com/solution/LeetCode/content/3785/

class Solution {
    private boolean flag;
    public boolean makesquare(int[] nums) {
        int temp = 0;
        for (int i = 0; i < nums.length; i++) {
            temp += nums[i];
        }
        if (nums.length == 0 || temp % 4 != 0)
            return false;
        int count[] = new int[4];
        Arrays.sort(nums);
        dfs(nums, count, nums.length-1,temp/4);
        return flag;
    }
    private void dfs(int[] nums, int[] count, int x,int avg) {
        if (x == -1) {
            for (int i = 0; i < 3; i++) {
                if (count[i] != count[i + 1])
                    return;
            }
            flag = true;
        } else {
            count[0] += nums[x];
            if(count[0]<=avg)dfs(nums, count, x - 1,avg);
            count[0] -= nums[x];
            count[1] += nums[x];
            if(count[1]<=avg)dfs(nums, count, x - 1,avg);
            count[1] -= nums[x];
            count[2] += nums[x];
            if(count[2]<=avg)dfs(nums, count, x - 1,avg);
            count[2] -= nums[x];
            count[3] += nums[x];
            if(count[3]<=avg)dfs(nums, count, x - 1,avg);
            count[3] -= nums[x];
        }
    }
}
全部评论

相关推荐

面试拷打成m:我感觉他说的挺对的,感觉我找不到工作也要去送外卖了,至少饿不死
点赞 评论 收藏
分享
09-01 11:31
门头沟学院 Java
buul:七牛云的吧,感觉想法是好的,但是大家没那么多时间弄他这个啊。。。不知道的还以为他是顶尖大厂呢还搞比赛抢hc,只能说应试者的痛苦考察方是无法理解的,他们只会想一出是一出
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务