一块40克的砝码,摔成4块,利用天平,刚好可以称出1~40g所有整数克,问:这4块分别是多少克

 1     public static void main(String[] args) {
 2         List<Integer> list = new ArrayList<>();//记录每组数的值 每组数a<=b<=c<=d
 3         List<Integer> rlist = new ArrayList<>();//记录最后的结果
 4         
 5         for(int i = 1; i <= 10 ; i++) {
 6             for(int j = i; j <= 13 ; j++) {
 7                 for(int k = j; k <= 19 ; k++) {
 8                     list.add(i);
 9                     list.add(j);
10                     list.add(k);
11                     list.add(40-i-j-k);
12                 }
13             }    
14         }
15         
16         int a,b,c,d;
17         int len = list.size()/4;
18         for (int i = 0; i < len; i++) {
19             a = list.get(4*i);
20             b = list.get(4*i+1);
21             c = list.get(4*i+2);
22             d = list.get(4*i+3);
23             if(result(a, b, c, d)) {
24                 rlist.add(a);
25                 rlist.add(b);
26                 rlist.add(c);
27                 rlist.add(d);
28             }
29         }
30         len = rlist.size()/4;
31         for(int i = 0; i < len; i++) {
32             System.out.println("40 = "+rlist.get(4*i)+" + "+rlist.get(4*i+1)+" + "+rlist.get(4*i+2)+" + "+rlist.get(4*i+3));
33         }
34     }
35     
36     public static boolean result(int a,int b,int c,int d){
37         TreeSet<Integer> set = new TreeSet<>();
38         int[] arr = {-1,0,1};
39         for (int i = 0; i < arr.length; i++) {
40             for (int j = 0; j < arr.length; j++) {
41                 for (int k = 0; k < arr.length; k++) {
42                     for (int l = 0; l < arr.length; l++) {
43                         int sum = a*arr[i]+b*arr[j]+c*arr[k]+d*arr[l];
44                         
45                         if(sum > 0) set.add(sum);
46                     }
47                 }
48             }
49         }
50         if(set.size() == 40)
51             return true;
52         else
53             return false;
54     }

 

posted @ 2018-11-17 21:51  束发读诗书  阅读(1014)  评论(0编辑  收藏  举报