题解 | #农场的奶牛分组II#

农场的奶牛分组II

https://www.nowcoder.com/practice/ae745225d12f44ca9e84486d051edbfa

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param weights int整型一维数组
     * @return bool布尔型
     */
    public boolean canPartitionII (int[] weights) {
        // write code here
        int total = 0;
        for (int i = 0; i < weights.length; i++) {
            total += weights[i];
        }
        if (total % 3 != 0) {
            return false;
        }
        return search(weights, 0, 0, 0, 0);
    }

    public boolean search(int[] weights, int index, int a, int b, int c) {
        if (index==weights.length && a == b && b == c) {
            return true;
        }else if(index==weights.length){
            return false;
        } 
        return search(weights, index + 1, a + weights[index], b, c)
               || search(weights, index + 1, a , b + weights[index], c)
               || search(weights, index + 1, a, b, c + weights[index]);
    }


}

本题我采用的是递归算法,所用编程语言是java。

我考虑使用三个桶往三个方向进行深度遍历,只要有一个方向返回true则整个深度遍历过程返回true,否则返回false。

全部评论
有问题,不能保证a,b,c就是目标和的1/3
点赞 回复 分享
发布于 2024-05-19 14:54 北京
绝个屁,他这算法就压根不对。之所以跑过,只不过是因为用例数不够
点赞 回复 分享
发布于 2023-08-24 22:00 江苏
这思路绝了
点赞 回复 分享
发布于 2023-08-09 22:41 陕西

相关推荐

哈哈哈哈哈哈哈哈哈哈这个世界太美好了
凉风落木楚山秋:毕业出路老师不管,你盖个章他好交差就完事了,等你盖完毕业了就不关他事情了
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:25
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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