题解 | #数组分组#

数组分组

https://www.nowcoder.com/practice/9af744a3517440508dbeb297020aca86

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        List<Integer> arrList = new ArrayList<Integer>();
        while (sc.hasNext()) {
            int n = sc.nextInt();
            int sum = 0, sum5 = 0, sum3 = 0;
            for (int i = 0; i < n; i++) {
                int cur = sc.nextInt();
                if (cur % 5 == 0) {
                    sum5 += cur;
                } else if (cur % 3 == 0) {
                    sum3 += cur;
                } else {
                    arrList.add(cur);
                }

                sum += cur;
            }

            if (sum % 2 != 0) {
                System.out.println(false);
                return;
            }

            int gap = sum / 2 - sum5;
            boolean res = canfill(gap, arrList, 0);
            System.out.println(res);
        }
    }

    public static boolean canfill(int gap, List<Integer> restList, int index ) {
        if (index == restList.size()) {
            return gap == 0;
        }

        return canfill(gap - restList.get(index), restList, index + 1) ||
               canfill(gap, restList, index + 1);
    }

}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务