题解 | #数位染色#

数位染色

http://www.nowcoder.com/practice/adf828f399de4932955734a4eac12757


// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str = in.next();
            String res = process(str) ? "Yes" : "No";
            System.out.println(res);
        }
    }
    
    public static boolean process(String str) {
        if (str == null || str.length() < 1) {
            return false;
        }
        char[] arr = str.toCharArray();
        int sum = 0;
        int n = arr.length;
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            sum += (arr[i] - '0');
            nums[i] = arr[i] - '0';
        }
        int half = sum / 2;
        if (sum % 2 != 0) {
            return false;
        }
        boolean[] dp = new boolean[half + 1];
        dp[0] = true;
        dp[nums[0]] = true;
        for (int i = 1; i < n; i++) {
            for (int j = half; j >= nums[i]; j--) {
                dp[j] = dp[j] || dp[j - nums[i]];
            }
            if (dp[half]) {
                return true;
            }
        }
        return false;
    }
    
    
}
全部评论

相关推荐

01-12 20:31
东北大学 Java
点赞 评论 收藏
分享
01-30 22:03
门头沟学院 Java
用微笑面对困难:我滴妈,【俩月】【实习】【主管】仨debuff吃满了,独立设计开发的项目写了绝大占比的运营板块,你独立开发,那维护、问题复盘、日志更新、bug、策划书全是自己整的? 不建议写那么大,可以从小出发更容易
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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