幸运的袋子, 网易笔试题

排序+深搜+剪枝

import java.util.*;
public class Main {
    static int dfs(int[] a, int n, int u, long sum, long pi) {
        int res = 0;
        for(int i=u; i < n; i++) {
            if(sum+a[i] > pi*a[i]) {
                res ++;
                res += dfs(a, n, i+1, sum+a[i], pi*a[i]);
            } else if(a[i] == 1) {
                res += dfs(a, n, i+1, sum+a[i], pi*a[i]);
            } else  break;
            while(i < n-1 && a[i] == a[i+1]) i++;
        }
        return res;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for(int i=0; i < n; i++) { a[i] = sc.nextInt();}
        Arrays.sort(a);
        int res = dfs(a,n, 0, 0L, 1L);
        //int res = find(a, 0,0, 1);
        System.out.println(res);
    }
}

你可能感兴趣的:(幸运的袋子, 网易笔试题)