百度4.12第三题,大佬看下对不对

public class Baidu {
    public static void main(String[] args) {
        //第三题
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        sc.nextLine();
        for (int i = 0; i < t; i++) {
            Map<Integer, Integer> map = new HashMap<>();
            int n = sc.nextInt();
            int k = sc.nextInt();
            sc.nextLine();
            int[] arr = new int[n];
            for (int j = 0; j < n; j++) {
                arr[j] = sc.nextInt();
            }
            method(arr,map,0,k,0,0);
            int ans=0;
            for(Integer key:map.keySet()){
                if(key%2==0)
                    ans+=map.get(key);
            }
            System.out.println(ans);
            sc.nextLine();
        }
    }

    public static void method(int[] arr, Map<Integer,Integer>map,int index,int k,int num,int add){
        if(num==k){
            int val=map.getOrDefault(add,0);
            val+=1;
            map.put(add,val);
            return;
        }
        for(int i=index;i<arr.length;i++){
            add+=arr[i];
            num++;
            method(arr,map,i+1,k,num,add);
            add-=arr[i];
            num--;
        }
    }
}

#百度笔试##实习##笔试题目#
全部评论
预处理一下组合数 然后奇数选多少个偶数选多少个就可以了 过了100%
点赞 回复 分享
发布于 2022-04-13 10:34
深搜我就过了20
点赞 回复 分享
发布于 2022-04-12 23:21
DFS不会超时嘛
点赞 回复 分享
发布于 2022-04-12 21:47

相关推荐

评论
1
3
分享

创作者周榜

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